// ALT


var altformChanged = false;

function altform_changed() {
	altformChanged = false;
	if ( $('altinfosubmit').disabled ) {
		$('altinfosubmit').disabled = false;
	}
}


function altform_show(id) {
	if ( $('altform').className == 'brick' ) {
		altform_hide(); // crazyone
	}
	altformChanged = false;
	$('altinfosubmit').disabled = true;
	// set the stage
	$('goalview').className = 'hidden';
	$('altform').className = 'brick'; // crazyone
	$('altaddformtitle' ).className = ( id == 0 ? 'formtitle' : 'hidden' );
	$('alteditformtitle').className = ( id != 0 ? 'formtitle' : 'hidden' );
	// set the fields
	if ( id > 0 && goal.alts && typeof(goal.alts[id]) != 'undefined' ) {
		var alt = goal.alts[id];
	} else {
		id = 0;
		var alt = {
			name: '',
			descript: false,
			price: 0,
			public: 0,
			locked: 0
		};
	}
	$('altinfoid').value        = id;
	$('altnamefield').value     = alt.name;
	$('altdescriptfield').value = ( alt.descript ? alt.descript : '' );
	$('altpricefield').value    = ( alt.price != 0 ? parseFloat(alt.price).toFixed(2) : '' );
	if ( $('alturlfield') ) {
		$('alturlfield').value    = ( alt.url && alt.url != '' ? alt.url : 'http://' );
	}
	if ( $('altpublicfield') ) {
		$('altpublicfield').checked = alt.public != 0;
		$('altlockedfield').checked = alt.locked != 0;
	}
	$('altnamefield').focus();
}

function altform_hide() {
	if ( altformChanged ) {
		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;
		}
		altformChanged = false;
	}
	// set the stage
	$('goalview').className = 'brick';
	$('altform').className = 'hidden'; // crazyone
}



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


function altform_submit() {
	// if editing
	if ( $('altinfoid').value != 0 ) {
		// if first with changed price
		if ( goal.usercosts == 0 && $('altpricefield').value > 0 ) {
			// warn them
			if ( !confirm('WARNING:\n\nThis will remove all comparisons for this decision option.\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('alt'),
		{
			//method: 'get',
			parameters: $('altinfoform').serialize(true),
			onSuccess: function(response) {
				var xml = api_handle(response);
				var res = node_value(xml.getElementsByTagName('res')[0]);
				var aid = node_value(xml.getElementsByTagName('altid')[0]);
				var nextstep = node_value(xml.getElementsByTagName('nextstep')[0]);
				var newprogress = node_value(xml.getElementsByTagName('progress')[0]);
				if ( res == 1 ) {
					// hide edit altinfo panel
					altform_hide();
					// if add, first add divs with needed ids
					if ( $('altinfoid').value == 0 ) {
						// save this to array
						goal.alts[aid] = {
							name: $('altnamefield').value,
							descript: $('altdescriptfield').value,
							url: ( $('alturlfield') && $('alturlfield').value != '' && $('alturlfield').value != 'http://' ? $('alturlfield').value : '' ),
							price: ( !isNaN(parseFloat($('altpricefield').value)) ? parseFloat($('altpricefield').value).toFixed(2) : 0 ),
							public: ( $('altpublicfield') && $('altpublicfield').checked ? 1 : 0 ),
							locked: ( $('altlockedfield') && $('altlockedfield').checked ? 1 : 0 )
						};
						goal.altscnt = parseInt(goal.altscnt, 10) + 1;
						evallinks_toggle();
						$('addmorealtsbutton').className = ( goal.altscnt < 3 ? 'brick' : 'hidden' );
						// put it on stage
						$('altlist').appendChild(
							// create alt view nodes
							Builder.node(
								'div',
								{ className: 'altviewinfo' },
								[
									Builder.node(
										'div',
										{ /*id: 'alt' + aid + 'namelabel',*/ className: 'altviewtitle', style: 'cursor: move;' },
										[
											Builder.node(
												'span',
												{ id: 'alt' + aid + 'namelabel' },
												[ Builder._text($('altnamefield').value) ]
											)
										]
									),
									Builder.node(
										'div',
										{ className: 'goalaltprice' },
										[
											Builder._text('Price: '),
											Builder.node(
												'span',
												{ id: 'alt' + aid + 'pricelabel' },
												[
													Builder._text(( !isNaN(parseFloat($('altpricefield').value)) ? parseFloat($('altpricefield').value).toFixed(2) : 'N/A' ))
												]
											),
											// help?
											Builder.node(
												'a',
												{ href: '#', onmouseover: 'ttip(\'' + b64_encode(godess_strings.altpricehelp) + '\');', onmouseout: 'ttiphide();' },
												[
													Builder.node(
														'sup',
														[ Builder._text('What is this?') ]
													)
												]
											)
										]
									),
									Builder.node(
										'div',
										{ className: 'goalviewdescript' },
										[
											Builder._text('Description: '),
											Builder.node(
												'span',
												{ id: 'alt' + aid + 'descriptlabel' },
												[
													Builder._text(( $('altdescriptfield').value != '' ? $('altdescriptfield').value : '<em>N/A</em>' ))
												]
											)
										]
									),
									Builder.node(
										'div',
										{ className: 'rowitembuttons' },
										[
											Builder.node(
												'button',
												{ type: 'button', onclick: 'altform_show(' + aid + ');' },
												[
													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: 'alt_delete(' + aid + ');' },
												[
													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' })
								]
							)
						);
						if ( goal.locked == 0 ) {
							sortableAlts  = Sortable.create(
								'altlist',
								{
									ghosting: true,
									tag: 'div',
									only: 'altviewinfo',
									handle: 'altviewtitle',
									onUpdate: updateOrderAlts
								}
							);
						}
					} else {
						// update array
						goal.alts[aid].name = $('altnamefield').value;
						goal.alts[aid].descript = $('altdescriptfield').value;
						goal.alts[aid].url = ( $('alturlfield') && $('alturlfield').value != '' && $('alturlfield').value != 'http://' ? $('alturlfield').value : '' );
						goal.alts[aid].price = ( !isNaN(parseFloat($('altpricefield').value)) ? parseFloat($('altpricefield').value).toFixed(2) : 0 );
						if ( $('altpublicfield') ) {
							goal.alts[aid].public = $('altpublicfield').checked ? 1 : 0;
							goal.alts[aid].locked = $('altlockedfield').checked ? 1 : 0;
						}
					}
					// now update labels with new stuff
					if ( goal.alts[aid].url != '' ) {
						$('alt' + aid + 'namelabel').innerHTML = '<a href="' + goal.alts[aid].url + '" target="_blank">' + goal.alts[aid].name + '</a>';
					} else {
						$('alt' + aid + 'namelabel').innerHTML = $('altnamefield').value;
					}
					$('alt' + aid + 'descriptlabel').innerHTML = ( $('altdescriptfield').value != '' ? $('altdescriptfield').value : '<em>N/A</em>' );
					$('alt' + aid + 'pricelabel').innerHTML = ( !isNaN(parseFloat($('altpricefield').value)) ? parseFloat($('altpricefield').value).toFixed(2) : 'N/A' );
					if ( $('alt' + aid + 'publicfield') ) {
						$('alt' + aid + 'publiclabel').innerHTML = ( $('alt' + aid + 'publicfield').checked ? 'Yes' : 'No' );
						$('alt' + aid + 'lockedlabel').innerHTML = ( $('alt' + aid + 'lockedfield').checked ? 'Yes' : 'No' );
					}
					//Description of Proposal A
					next_step_set(b64_decode(nextstep));
					progress_bar_set(newprogress);
				} else {
					var err = node_value(xml.getElementsByTagName('err')[0]);
					// alt add/edit
					if ( err == 259 ) {
						altinfonotice_set('Please name your decision option. You are the only person that will benefit from that; you will know how to recognize it. ;-)');
						$('goalnamefield').focus();
					} else if ( err == 239 ) {
						altinfonotice_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 ) {
						altinfonotice_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 == 261 ) {
						altinfonotice_set('There was a problem while adding your option. Please try again. If it still does not work, please contact support.');
					} else if ( err == 263 ) {
						altinfonotice_set('It looks like you are trying to edit a decision option that does not exist. Please <a href="#" onclick="window.location.reload(true);return false;">refresh this page</a> to see current options.');
					} else if ( err == 265 ) {
						altinfonotice_set('It looks like you can not edit this decision option, 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 == 267 ) {
						altinfonotice_set('There was a problem while updating your decision option. Please try again. If it still does not work, please contact support.');
					} else if ( err == 253 ) {
						altinfonotice_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 alt_delete(id) {
	if ( !confirm('This will delete this decision option.\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('alt_del'),
		{
			//method: 'get',
			parameters: params,
			onSuccess: function(response) {
				var xml = api_handle(response);
				var res = node_value(xml.getElementsByTagName('res')[0]);
				var aid = node_value(xml.getElementsByTagName('altid')[0]);
				var nextstep = node_value(xml.getElementsByTagName('nextstep')[0]);
				var newprogress = node_value(xml.getElementsByTagName('progress')[0]);
				if ( res == 1 ) {
					// remove this alt from array
					if ( typeof(goal.alts[aid]) != 'undefined' ) {
						delete goal.alts[aid];
					}
					// decrement the counter
					goal.altscnt = parseInt(goal.altscnt, 10) - 1;
					// turn off evaluate links if needed
					evallinks_toggle();
					// now remove it from DOM
					var rel = $('alt' + aid + 'namelabel');
					if ( rel ) {
						rel.parentNode.parentNode.parentNode.removeChild(rel.parentNode.parentNode);
						sortableAlts  = Sortable.create(
							'altlist',
							{
								ghosting: true,
								tag: 'div',
								only: 'altviewinfo',
								handle: 'altviewtitle',
								onUpdate: updateOrderAlts
							}
						);
					}
					next_step_set(b64_decode(nextstep));
					progress_bar_set(newprogress);
				} else {
					var err = node_value(xml.getElementsByTagName('err')[0]);
					// alt delete
					if ( err == 239 ) {
						altinfonotice_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 ) {
						altinfonotice_set('Goal not found. We will have to be redirected to your goals page.');
						window.location.href = '/goals.php';
					} else if ( err == 241 ) {
						altinfonotice_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 == 263 ) {
						altinfonotice_set('It looks like you are trying to delete a decision option that does not exist. Please <a href="#" onclick="window.location.reload(true);return false;">refresh this page</a> to see current options.');
					} else if ( err == 265 ) {
						altinfonotice_set('It looks like you can not delete this option, 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 == 255 ) {
						altinfonotice_set('There was a problem while deleting your decision option. Please try again. If it still does not work, please contact support.');
					}
				}
			},
			onFailure: function() { bar_error_show('API call failed, something went wrong...') }
		}
	);
}



