if (typeof DeskPRO == 'undefined') DeskPRO = {};
if (typeof DeskPRO.User == 'undefined') DeskPRO.User = {};
if (typeof DeskPRO.User.Ideas == 'undefined') DeskPRO.User.Ideas = {};



/**
 * Constructor
 *
 * @option {String} helpdesk_url       The url to the save votes page
 */
DeskPRO.User.Ideas.NewIdea = function(options, lang) {
	this.obj_name = 'dp_newidea_' + ((new Date()).getTime());
	window[this.obj_name] = this;
	
	this.options = {
		helpdesk_url: '.',
		button_sel: '.dp-newidea-btn',
		show_name_field: false
	};
	jQuery.extend(this.options, options||{});
	
	this.lang = {
		'link': 'Your new idea has been submitted! Click here to view your idea: ',
		'form_title': 'My idea is about...',
		'form_description': 'Description:',
		'form_category': 'Category:',
		'form_user_name': 'Your name (optional):',
		'similar_ideas': 'Before we save your idea, are any of these ideas like yours?',
		'submit': 'Submit Idea',
		'submit_after_similar': 'No, submit my new idea',
		'title': 'Submit An Idea',
		'ideas_link': 'View Other Ideas',
		'error_title_required': 'Please enter a title',
		'error_title_toolong': 'Please enter a title that is less than 90 characters long',
		'error_message_required': 'Please enter a description',
		'error_message_toolong': 'Your description is a little too long. Try making it shorter.',
		'error_category_id_required': 'Please choose a category',
		'errors_explain': 'Please correct these errors and try again:'
	};
	jQuery.extend(this.lang, lang||{});
	
	this.div = null;
	this.using_cats = false;
	this.seen_search = false;
	this.real_submit_next = false;

	var self = this;	
	jQuery(document).ready(function() {
		self.init();
	});
};



/**
 * When the document is loaded, we can init the markup and even handlers
 */
DeskPRO.User.Ideas.NewIdea.prototype.init = function() {
	this.initStyle();
	this.initHtml();
	
	// Init categories
	var self = this;
	jQuery.ajax({
		url: this.options.helpdesk_url + '/ideas.php?do=ajaxcats',
		dataType: 'jsonp',
		success: function (data) {
			if (data.is_cats) {
				self.using_cats = true;
				
				var html = [];
				html.push(self.lang['form_category']);
				html.push('<br />');
				html.push(data.cats_html);
				html = html.join('');
				jQuery('.dp-submit-form-cat', this.div).html(html).show();
			}
		}
	});
	
	jQuery(this.options.button_sel).click(function(ev) {
		ev.preventDefault();
		ev.stopPropagation();
		self.handleButtonClick(this);
	});
	
	// Clicks that bubble to the div should stop
	// so they dont reach the document which closes it
	this.div.click(function(ev) {
		ev.stopPropagation();
	});
	
	// When the document is clicked, we hide the newidea div
	jQuery(document).click(function() {
		self.div.hide();
	});
	
	// Intercept submit on form
	jQuery('form', this.div).submit(function(ev) {
		self.handleSubmit(ev);
	});
	
	// Click the button after viewing search results
	jQuery('.dp-searchresults-submit', this.div).click(function() {
		self.seen_search = true;
		jQuery('form', self.div).submit();
	});
};


/**
 * Hanles submitting the form.
 */
DeskPRO.User.Ideas.NewIdea.prototype.handleSubmit = function(ev) {
	
	ev.preventDefault();

	var data = {};
	data['title'] = jQuery('input[name="title"]', this.div).val();
	data['message'] = jQuery('textarea[name="message"]', this.div).val();
	data['user_name'] = jQuery('input[name="user_name"]', this.div).val();
	if (this.using_cats) {
		data['category_id'] = parseInt(jQuery('select[name="category_id"] option:selected', this.div).val());
	}
	if (this.seen_search) {
		data['saw_suggestions'] = 1;
	}
	
	if (!this.validateForm(data)) {
		ev.preventDefault();
		return;
	}

	var total_len =	data['title'].length + data['message'].length + data['user_name'].length;
		
	// If this is a big long idea, we have to submit a real POST form
	// because we cant use JSONP, which is GET, and GET has a general
	// maximum length of 2000 characters
	if (total_len > 1800) {
		// So we just return and dont prevent default behavior
		return;
	}
	
	// Maybe we want to submit for real
	if (this.real_submit_next) {
		this.real_submit_next = false;
		return;
	}
	
	// Dont submit the real <form>
	ev.preventDefault();
	
	$('input[type="submit"]', this.div).val('...').attr('disabled', 'disabled'); // "loading"
	
	var self = this;
	jQuery.ajax({
		url: this.options.helpdesk_url + '/ideas.php?do=new&ajax=1&process=1',
		data: data,
		dataType: 'jsonp',
		success: function(data) {
			self.handleSubmitReply(data);
		}
	});
	
	self.seen_search = false;
};



/**
 * Handle the ajax reply from the server
 */
DeskPRO.User.Ideas.NewIdea.prototype.handleSubmitReply = function(data) {

	console.log('ajaxdata: %o', data);

	// Handle errors by just posting the form
	// We should've caught basic errors about length already, so anything
	// else can be handled through the real page
	if (data.error) {
		this.real_submit_next = true;
		$('form', this.div).submit();
		return;
	}
	
	if (data.suggestions) {
		$('.dp-submit-form', this.div).hide();
		$('.dp-searchresults-list', this.div).html(data.suggestions_html);
		$('.dp-searchresults', this.div).show();
		return;
	}
	
	$('.dp-submit-form', this.div).hide();
	$('.dp-searchresults', this.div).hide();
	$('.dp-submit-done-link', this.div).html('<a href="'+this.options.helpdesk_url+'/ideas.php?'+data.idea_url_part+'">'+data.idea_title+'</a>');
	$('.dp-submit-done', this.div).show();
};



/**
 * Validates the form before sending it off
 */
DeskPRO.User.Ideas.NewIdea.prototype.validateForm = function(data) {
	var errors = [];
	
	var title_len = data['title'].length;
	var message_len = data['message'].length;
	var category_id = 0;
	if (this.using_cats) {
		var category_id = data['category_id'];
	}
	
	if (title_len < 1) {
		errors.push(this.lang['error_title_required']);
	} else if (title_len > 90) {
		errors.push(this.lang['error_title_toolong']);
	}
	if (message_len < 1) {
		errors.push(this.lang['error_message_required']);
	} else if (message_len > 5000) {
		errors.push(this.lang['error_message_toolong']);
	}
	if (this.using_cats && category_id == 0) {
		errors.push(this.lang['error_category_id_required']);
	}
	
	if (errors.length) {
		var errors = this.lang['errors_explain'] + "\n\n- " + errors.join("\n- ");
		alert(errors);
		return false;
	}
	
	return true;
};



/**
 * When an 'open' button is clicked, we need to show the newidea div
 */
DeskPRO.User.Ideas.NewIdea.prototype.handleButtonClick = function(element) {
	var el = jQuery(element);
	
	var pos = el.offset();
	this.div.css({
		left: pos.left,
		top: pos.top
	});
	this.div.show();
};



/**
 * Initiate the newidea div HTML and append it to the document.
 */
DeskPRO.User.Ideas.NewIdea.prototype.initHtml = function() {
	var html = [];
	html.push('<div class="dp-newidea" id="'+this.obj_name+'">');
	html.push('<div class="dp-header">');
		html.push('<span class="dp-header-ideas-link"><a href="' + this.options.helpdesk_url + '/ideas.php">' + this.lang['ideas_link'] + '</a></span>');
		html.push('<span class="dp-header-title">' + this.lang['title'] + '</span>');
	html.push('</div>');
	html.push('<div class="dp-body">');
	html.push('<div class="dp-searchresults" style="display:none">');
		html.push(this.lang['similar_ideas']);
		html.push('<div class="dp-searchresults-list"></div>');
		html.push('<input type="button" class="dp-searchresults-submit" value="' + this.lang['submit_after_similar'] + '" />');
	html.push('</div>');
	html.push('<div class="dp-submit-done" style="display:none">');
		html.push(this.lang['link']);
		html.push('<div class="dp-submit-done-link"></div>');
	html.push('</div>');
	html.push('<div class="dp-submit-form">');
		html.push('<form action="'+this.options.helpdesk_url+'/ideas.php?do=new" method="post">');
		html.push('<div class="dp-submit-form-username"' + (!this.options.show_name_field ? ' style="display:none"' : '') + '>');
		html.push(this.lang['form_user_name']);
		html.push('<br /><input type="text" class="dp-input" name="user_name" value="" /><br />');
		html.push('</div>');
		html.push('<div class="dp-submit-form-cat" style="display:none"></div>');
		html.push(this.lang['form_title']);
		html.push('<br /><input type="text" class="dp-input" name="title" value="" /><br />');
		html.push(this.lang['form_description']);
		html.push('<br /><textarea name="message" class="dp-textarea"></textarea><br />');
		html.push('<input type="submit" value="'+this.lang['submit']+'" />');
		html.push('</form>');
	html.push('</div>');
	html.push('</div>');
	html.push('</div>');
	html = html.join('');

	jQuery(document.body).append(html);
	
	this.div = jQuery('#' + this.obj_name);
};



/**
 * Initiate the style used for the newidea div and append it to the head
 */
DeskPRO.User.Ideas.NewIdea.prototype.initStyle = function() {
	
	var html = [];
	html.push('<style type="text/css">');
	html.push('.dp-newidea { display: none; position: absolute; background: #F1F1F1; border: 2px solid #617185; width: 400px; color: #000; -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; }');
	html.push('.dp-newidea .dp-header { background-color: #C8CCD3; padding: 4px; }');
	html.push('.dp-newidea .dp-header .dp-header-ideas-link { float:right; }');
	html.push('.dp-newidea .dp-header .dp-header-ideas-link a { color: #000; text-decoration: underline; }');
	html.push('.dp-newidea .dp-header .dp-header-title { font-weight: bold; }');
	html.push('.dp-newidea .dp-body { padding: 7px; }');
	html.push('.dp-newidea .dp-body { padding: 7px; }');
	html.push('.dp-newidea .dp-input { background-color: #fff; color: #000; border: 1px solid #888; padding: 3px; margin: 4px; width: 90%; }');
	html.push('.dp-newidea .dp-textarea { background-color: #fff; color: #000; border: 1px solid #888; padding: 3px; margin: 4px; width: 90%; height: 100px; }');
	html.push('.dp-newidea .dp-searchresults .dp-searchresults-list { height: 100px; overflow: hidden; }');
	html.push('.dp-newidea .dp-searchresults .dp-searchresults-list ul { margin: 0 0 0 20px; }');
	html.push('.dp-newidea .dp-searchresults .dp-searchresults-list ul li { list-style-type: disc; margin: 5px 0 5px 0; }');
	html.push('.dp-newidea .dp-searchresults .dp-searchresults-list ul li a { color: #364658; text-decoration: underline; }');
	html.push('</style>');
	html = html.join('');
	
	jQuery('head').append(html);
};
