// CRIT


var critformChanged = false;

function critform_changed() {
	critformChanged = false;
	if ( $('critinfosubmit').disabled ) {
		$('critinfosubmit').disabled = false;
	}
}


function critform_show(id) {
	if ( $('critform').className == 'brick' ) {
		critform_hide(); // crazyone
	}
	critformChanged = false;
	$('critinfosubmit').disabled = true;
	// set the stage
	$('goalview').className = 'hidden';
	$('critform').className = 'brick'; // crazyone
	$('critaddformtitle' ).className = ( id == 0 ? 'formtitle' : 'hidden' );
	$('criteditformtitle').className = ( id != 0 ? 'formtitle' : 'hidden' );
	// set the fields
	if ( id > 0 && goal.crits && typeof(goal.crits[id]) != 'undefined' ) {
		var crit = goal.crits[id];
	} else {
		id = 0;
		var crit = {
			name: '',
			descript: false,
			quant: 0,
			public: 0,
			locked: 0
		};
	}
	$('critinfoid').value        = id;
	$('critnamefield').value     = crit.name;
	$('critdescriptfield').value = ( crit.descript ? crit.descript : '' );
	$('critquantfield').checked  = ( crit.quant != 0 );
	$('crittypefield').value     = crit.quant;
	$('crittypefield').disabled  = ( crit.quant == 0 );
	if ( $('critpublicfield') ) {
		$('critpublicfield').checked = crit.public != 0;
		$('critlockedfield').checked = crit.locked != 0;
	}
	$('critnamefield').focus();
}

function critform_hide() {
	if ( critformChanged ) {
		if ( !confirm('You have changed the contents of this form, and did not click the Save button.\n\nAre you sure you wish to continue?') ) {
			return;
		}
		critformChanged = false;
	}
	// set the stage
	$('goalview').className = 'brick';
	$('critform').className = 'hidden'; // crazyone
}



function critinfonotice_set(txt, cls) {
	if ( !cls ) cls = 'api_error';
	$('critinfonotice').innerHTML = txt;
	$('critinfonotice').className = cls;
}


function critform_submit() {
	// if editing
	if ( $('critinfoid').value != 0 ) {
		// if changed type
		if ( goal.crits[$('critinfoid').value]['quant'] != $('crittypefield').value ) {
			// if changed between quant/qual
			if ( goal.crits[$('critinfoid').value]['quant'] == 0 || $('crittypefield').value == 0 ) {
				// if it has evals
				if ( goal.evalsmade[$('critinfoid').value] && goal.evalsmade[$('critinfoid').value] > 0 ) {
					// warn them
					if ( !confirm('WARNING:\n\nThis will remove all comparisons for this criteria.\n\n\n\nAre you sure you wish to continue?') ) {
						return;
					}
				}
			}
		}
	}
	bar_loader_show('Sending Data...');
	// return true; // don't use ajax
	new Ajax.Request(
		apiurl('crit'),
		{
			//method: 'get',
			parameters: $('critinfoform').serialize(true),
			onSuccess: function(response) {
				var xml = api_handle(response);
				var res = node_value(xml.getElementsByTagName('res')[0]);
				var cid = node_value(xml.getElementsByTagName('critid')[0]);
				var nextstep = node_value(xml.getElementsByTagName('nextstep')[0]);
				var newprogress = node_value(xml.getElementsByTagName('progress')[0]);
				if ( res == 1 ) {
					// hide edit critinfo panel
					critform_hide();
					// if add, first add divs with needed ids
					if ( $('critinfoid').value == 0 ) {
						// save this to array
						goal.crits[cid] = {
							name: $('critnamefield').value,
							descript: $('critdescriptfield').value,
							quant: $('crittypefield').value,
							public: ( $('critpublicfield') && $('critpublicfield').checked ? 1 : 0 ),
							locked: ( $('critlockedfield') && $('critlockedfield').checked ? 1 : 0 )
						};
						goal.critscnt = parseInt(goal.critscnt, 10) + 1;
						evallinks_toggle();
						$('addmorecritsbutton').className = ( goal.critscnt < 3 ? 'brick' : 'hidden' );
						// put it on stage
						$('critlist').appendChild(
							// create crit view nodes
							Builder.node(
								'div',
								{ className: 'critviewinfo' },
								[
									Builder.node(
										'div',
										{ className: 'critviewtitle', style: 'cursor: move;' },
										[
											Builder.node(
												'div',
												{ id: 'critprogressbox' + cid, className: 'critprogressbox' },
												[
													Builder.node('span', [ Builder._text('Progress: ') ]),
													Builder.node(
														'div',
														{ id: 'critprogress' + cid, className: 'critprogress', title: '0%' },
														[
															Builder.node(
																'img',
																{
																	id: 'critprogressbar' + cid,
																	className: 'critprogressbar',
																	src: '/images/progressbar.gif',
																	height: '16',
																	border: '0',
																	alt: '0%',
																	title: '0%',
																	style: 'width: 0%;'
																}
															)
														]
													),
													Builder.node('br', { clear: 'all' }),
												]
											),
											Builder.node(
												'span',
												{ id: 'crit' + cid + 'namelabel' },
												[ Builder._text($('critnamefield').value) ]
											)
										]
									),
									Builder.node(
										'div',
										{ className: 'goalcritquant' },
										[
											Builder._text('Measurable: '),
											Builder.node('span', { id: 'crit' + cid + 'quantlabel' }, [ Builder._text(( $('critquantfield').checked ? "Yes ('" + ( $('crittypefield').value == 2 ? 'more' : 'less' ) + "' is better)" : 'No' )) ]),
											// help?
											Builder.node(
												'a',
												{ href: '#', onmouseover: 'ttip(\'' + b64_encode(godess_strings.critquanthelp) + '\');', onmouseout: 'ttiphide();' },
												[
													Builder.node(
														'sup',
														[ Builder._text('What is this?') ]
													)
												]
											)
										]
									),
									Builder.node(
										'div',
										{ className: 'goalviewdescript' },
										[
											Builder._text('Description: '),
											Builder.node('span', { id: 'crit' + cid + 'descriptlabel' }, [ Builder._text(( $('critdescriptfield').value != '' ? $('critdescriptfield').value : '<em>N/A</em>' )) ])
										]
									),
									Builder.node(
										'div',
										{ className: 'rowitembuttons' },
										[
											// no need for "comparisons" button here
											Builder.node(
												'button',
												{
													type: 'button',
													id: 'crit' + cid + 'evallink',
													className: ( goal.altscnt > 2 && goal.critscnt > 2 ? 'inliner' : 'hidden' ),
													onclick: "window.location.href='/evaluate.php?g=" + goal.id + "&c=" + cid + "';"
												},
												[
													Builder.node(
														'img', {
															src: '/images/go.png',
															border: 0,
															alt: 'compare',
															title: 'compare'
														}
													),
													Builder._text(' '),
													Builder.node('strong', [ Builder._text('compare') ])
												]
											),
											Builder._text(' '),
											Builder.node(
												'button',
												{ type: 'button', onclick: 'critform_show(' + cid + ');' },
												[
													Builder.node(
														'img', {
															src: '/images/autumn/16x16/new.png',
															border: 0,
															alt: 'edit',
															title: 'edit'
														}
													),
													Builder._text(' '),
													Builder._text('edit')
												]
											),
											Builder._text(' '),
											Builder.node(
												'button',
												{ type: 'button', onclick: 'crit_delete(' + cid + ');' },
												[
													Builder.node(
														'img', {
															src: '/images/autumn/16x16/remove_(delete).png',
															border: 0,
															alt: 'delete',
															title: 'delete'
														}
													),
													Builder._text(' '),
													Builder._text('delete')
												]
											)
										]
									),
									Builder.node('br', { clear: 'all' })
								]
								// no need for evals/results divs here, gotta leave the page to fill up those
							)
						);
						sortableCrits = Sortable.create(
							'critlist',
							{
								ghosting: true,
								tag: 'div',
								only: 'critviewinfo',
								handle: 'critviewtitle',
								onUpdate: updateOrderCrits
							}
						);
					} else {
						// update array
						goal.crits[cid].name = $('critnamefield').value;
						goal.crits[cid].descript = $('critdescriptfield').value;
						goal.crits[cid].quant = $('crittypefield').value;
						if ( $('critpublicfield') ) {
							goal.crits[cid].public = $('critpublicfield').checked ? 1 : 0;
							goal.crits[cid].locked = $('critlockedfield').checked ? 1 : 0;
						}
					}
					// now update labels with new stuff
					$('crit' + cid + 'namelabel').innerHTML = $('critnamefield').value;
					$('crit' + cid + 'descriptlabel').innerHTML = ( $('critdescriptfield').value != '' ? $('critdescriptfield').value : '<em>N/A</em>' );
					$('crit' + cid + 'quantlabel').innerHTML = ( $('critquantfield').checked ? 'Yes' : 'No' );
					if ( $('critquantfield').checked ) {
						if ( $('crittypefield').value == 2 ) {
							$('crit' + cid + 'quantlabel').innerHTML += " ('more' is better)";
						} else {
							$('crit' + cid + 'quantlabel').innerHTML += " ('less' is better)";
						}
					}
					if ( $('crit' + cid + 'publicfield') ) {
						$('crit' + cid + 'publiclabel').innerHTML = ( $('critpublicfield').checked ? 'Yes' : 'No' );
						$('crit' + cid + 'lockedlabel').innerHTML = ( $('critlockedfield').checked ? 'Yes' : 'No' );
					}
					next_step_set(b64_decode(nextstep));
					progress_bar_set(newprogress);
				} else {
					var err = node_value(xml.getElementsByTagName('err')[0]);
					// crit add/edit
					if ( err == 243 ) {
						critinfonotice_set('Please name your criteria. You are the only person that will benefit from that; you will know how to recognize it. ;-)');
						$('goalnamefield').focus();
					} else if ( err == 239 ) {
						critinfonotice_set('It looks like you have no permission to edit goals. We will have to refresh your page, because you should not be able to use this form.');
						window.location.reload(true);
					} else if ( err == 241 ) {
						critinfonotice_set('It looks like you can not edit this goal, which can happen if the goal is not yours. If you wish to make a goal like this one, you can <a href="/goal.php?use=' + goal.code + '">use it to create your own</strong>.');
					} else if ( err == 245 ) {
						critinfonotice_set('There was a problem while adding your criteria. Please try again. If it still does not work, please contact support.');
					} else if ( err == 247 ) {
						critinfonotice_set('It looks like you are trying to edit a criteria that does not exist. Please <a href="#" onclick="window.location.reload(true);return false;">refresh this page</a> to see current criteria.');
					} else if ( err == 249 ) {
						critinfonotice_set('It looks like you can not edit this criteria, which can happen if the goal is not yours. If you wish to make a goal like this one, you can <a href="/goal.php?use=' + goal.code + '">use it to create your own</strong>.');
					} else if ( err == 251 ) {
						critinfonotice_set('There was a problem while updating your criteria. Please try again. If it still does not work, please contact support.');
					} else if ( err == 253 ) {
						critinfonotice_set('Goal not found. We will have to be redirected to your goals page.');
						window.location.href = '/goals.php';
					}
				}
			},
			onFailure: function() { bar_error_show('API call failed, something went wrong...') }
		}
	);
	return false;
}

function crit_delete(id) {
	if ( !confirm('This will delete this decision criteria.\n\nAre you sure you want to do this?') ) {
		return;
	}
	// 2do: are there any evals including this alternative?
	bar_loader_show('Deleting...');
	var params = {
		id: id,
		goal: goal.code
	};
	new Ajax.Request(
		apiurl('crit_del'),
		{
			//method: 'get',
			parameters: params,
			onSuccess: function(response) {
				var xml = api_handle(response);
				var res = node_value(xml.getElementsByTagName('res')[0]);
				var cid = node_value(xml.getElementsByTagName('critid')[0]);
				var nextstep = node_value(xml.getElementsByTagName('nextstep')[0]);
				var newprogress = node_value(xml.getElementsByTagName('progress')[0]);
				if ( res == 1 ) {
					// remove this crit from array
					if ( typeof(goal.crits[cid]) != 'undefined' ) {
						delete goal.crits[cid];
					}
					// decrement the counter
					goal.critscnt = parseInt(goal.critscnt, 10) - 1;
					// turn off evaluate links if needed
					evallinks_toggle();
					// now remove it from DOM
					var rel = $('crit' + cid + 'namelabel');
					if ( rel ) {
						rel.parentNode.parentNode.parentNode.removeChild(rel.parentNode.parentNode);
						sortableCrits = Sortable.create(
							'critlist',
							{
								ghosting: true,
								tag: 'div',
								only: 'critviewinfo',
								handle: 'critviewtitle',
								onUpdate: updateOrderCrits
							}
						);
					}
					next_step_set(b64_decode(nextstep));
					progress_bar_set(newprogress);
				} else {
					var err = node_value(xml.getElementsByTagName('err')[0]);
					// crit delete
					if ( err == 239 ) {
						critinfonotice_set('It looks like you have no permission to edit goals. We will have to refresh your page, because you should not be able to use this form.');
						window.location.reload(true);
					} else if ( err == 253 ) {
						critinfonotice_set('Goal not found. We will have to be redirected to your goals page.');
						window.location.href = '/goals.php';
					} else if ( err == 241 ) {
						critinfonotice_set('It looks like you can not edit this goal, which can happen if the goal is not yours. If you wish to make a goal like this one, you can <a href="/goal.php?use=' + goal.code + '">use it to create your own</strong>.');
					} else if ( err == 247 ) {
						critinfonotice_set('It looks like you are trying to delete a criteria that does not exist. Please <a href="#" onclick="window.location.reload(true);return false;">refresh this page</a> to see current criteria.');
					} else if ( err == 249 ) {
						critinfonotice_set('It looks like you can not delete this criteria, which can happen if the goal is not yours. If you wish to make a goal like this one, you can <a href="/goal.php?use=' + goal.code + '">use it to create your own</strong>.');
					} else if ( err == 257 ) {
						critinfonotice_set('There was a problem while deleting your criteria. Please try again. If it still does not work, please contact support.');
					}
				}
			},
			onFailure: function() { bar_error_show('API call failed, something went wrong...') }
		}
	);
}



