function toggleNode(id, class1, class2) {
  if ( typeof(id) == 'string' )
    elref = $(id);
  else
    elref = id;
  if ( elref === null ) return;
  elref.className = elref.className == class1 ? class2 : class1;
  return elref.className;
}

function stopEnterKey(evt) {
	var evt = ( evt ? evt : ( event ? event : null ) );
	if ( !evt ) return true;
	var node = ( evt.target ? evt.target : ( evt.srcElement ? evt.srcElement : null ) );
	// 13 == ENTER
	if ( evt.keyCode == 13 && node.type == "text" )  {
		// nope, don't submit
		return false;
	}
}

function setcookie(name, value, expires /*in seconds*/, path, domain, secure) {
    var d = new Date();
    d.setTime(d.getTime() + (expires * 1000));
	var cookieVar =
		name + "=" + escape(value) +
		( expires ? "; expires=" + d.toGMTString() : "" ) +
		( path ? "; path=" + path : "" ) +
		( domain ? "; domain=" + domain : "" ) +
		( secure ? "; secure" : "" )
	;
	document.cookie = cookieVar;
}

function nl2br(str) {
	if ( typeof(str) == "string" )
		return str.replace(/(\r\n)|(\n\r)|\r|\n/g,'<br />'); // '
	else
		return str;
}

function apiurl(r) {
	return '/api.php?r=' + r + '&rand=' + Math.random().toString();
}

//var userform_whitelist = [ 'login', 'password', 'reset', 'signup', 'welcome' ];
function userform_show(what) {
	/*
	// set the panel
	$('userformlogin').className = ( what == 'login' ? 'brick' : 'hidden' );
	$('userformpassword').className = ( what == 'password' ? 'brick' : 'hidden' );
	$('userformreset').className = ( what == 'reset' ? 'brick' : 'hidden' );
	if ( $('userformsignup') ) $('userformsignup').className = ( what == 'signup' ? 'brick' : 'hidden' );
	$('userformwelcome').className = ( what == 'welcome' ? 'brick' : 'hidden' );
	*/

	// set the email link
	if ( what == 'password' || what == 'welcome' ) {
		$('userformemailcheck' + what).href = 'http://www.' + $(what + 'emailfield').value.substr($(what + 'emailfield').value.indexOf('@') + 1) + '/';
	}

	// set the form
	// reset all input text fields to '', and all checkboxes to unchecked
	var frm = $('userformid' + what);
	var inp = frm.getElementsByTagName('input');
	for ( var i = 0; i < inp.length; i++ ) {
		if ( inp[i].type == 'checkbox' ) {
			inp[i].checked = false;
		} else if ( inp[i].type == 'text' || inp[i].type == 'password' ) {
			if ( inp[i].id && inp[i].id == what + 'emailfield' ) {
				if ( what != 'password' && what != 'welcome' ) {
					inp[i].value = '';
				}
			} else {
				inp[i].value = '';
			}
		}
	}
	//if signup, assign visitor info vars
	if ( what == 'signup' ) {
		// assign visitor info vars
		$('signupemailfield').value = visitor.email;
		$('signupfirstnamefield').value = visitor.firstname;
		$('signuplastnamefield').value = visitor.lastname;
	}

	// notice bar
	$('usernotice' + what).innerHTML = '';
	$('usernotice' + what).className = 'hidden';

	// set the stage
	//$('menu').className = 'hidden';
	$('content').className = 'hidden';
	//$('footer').className = 'hidden';

	// set the panel
	$('userformlogin').className = 'hidden';
	$('userformpassword').className = 'hidden';
	$('userformreset').className = 'hidden';
	if ( $('userformsignup') ) $('userformsignup').className = 'hidden';
	$('userformwelcome').className = 'hidden';
	$('userform' + what).className = 'brick'; // crazyone
	//if ( Modalbox && Modalbox.initialized ) Modalbox.hide();
	//Modalbox.show($('userform' + what), {title: $$('#userform' + what + ' h1 span')[0].innerHTML, width: 500});

	$(what + 'emailfield').focus();
	return false;
}

function userform_hide(what) {
	// set the stage
	//$('menu').className = 'brick';
	$('content').className = 'brick';
	//$('footer').className = 'brick';
	if ( $('userform' + what) ) {
		$('userform' + what).className = 'hidden'; // crazyone
	}
	//if ( Modalbox && Modalbox.initialized ) Modalbox.hide();
}



function userform_submit(action) {
	if ( typeof isPDA != 'undefined' ) return true;
	if ( $(action + 'emailfield').value == '' ) {
		alert('Email Field can not be left empty.');
		$('emailfield').focus();
		return false;
	}
	if ( action == 'welcome' || action == 'login' ) {
		if ( $(action + 'passwordfield').value.length < 4 ) {
			alert('Password Field can not be less than 4 characters long.');
			$(action + 'passwordfield').focus();
			return false;
		}
	}
	if ( action == 'password' ) {
		if ( $(action + 'codefield').value != '' ) {
			alert('Password Reset Code can not be left empty.');
			$(action + 'codefield').focus();
			return false;
		}
	}
	if ( action == 'password' && $(action + 'newpasswordfield').value.length > 0 ) {
		if ( $(action + 'newpasswordfield').value.length < 4 ) {
			alert('New Password Field can not be less than 4 characters long.');
			$(action + 'newpasswordfield').focus();
			return false;
		}
		if ( $(action + 'newpasswordfield').value != $(action + 'newpassword2field').value ) {
			alert('Passwords do not match. Please enter the new password again. Twice.');
			$(action + 'newpasswordfield').value = '';
			$(action + 'newpassword2field').value = '';
			$(action + 'newpasswordfield').focus();
			return false;
		}
	}
	if ( action == 'signup' ) {
		if ( $(action + 'firstnamefield').value == '' && $(action + 'lastnamefield').value == '' ) {
			alert('You can not leave both first and last name empty.');
			$(action + 'firstnamefield').focus();
			return false;
		}
	}
	$('userformsubmit' + action).disabled = true;
	bar_loader_show('Sending Data...');
	// return true; // don't use ajax
	new Ajax.Request(
		apiurl(action),
		{
			//method: 'get',
			parameters: $('userformid' + action).serialize(true),
			onSuccess: function(response) {
				var xml = api_handle(response);
				var res = node_value(xml.getElementsByTagName('res')[0]);
				if ( res == 1 ) {
					if ( action == 'signup' || action == 'reset' ) {
						//userform_hide();
						$('userformsubmit' + action).disabled = false;
						userform_show( action == 'signup' ? 'welcome' : 'password' );
					} else if ( action == 'login' || action == 'password' || action == 'welcome' ) {
						// by default redirect to homepage
						var redir = '/';
						if ( redirect2 != '' && redirect2.match(/^[a-zA-Z0-9_.\-]+$/) ) {
							// use page name only
							redir = '/' + redirect2 + '.php';
						} else if ( redirect4 != '' && redirect4.charAt(0) == '/' ) {
							// use full uri
							redir = redirect4;
						}
						// on logout page, force redirect to homepage
						// on other pages simply reload
						if ( pageName != 'logout' && redir == '' ) {
							// on other pages simply reload
							window.location.reload(true);
						} else {
							// on logout page, or if redirection is provided, redirect to home
							window.location.href = redir;
						}
						// do all kinds of stuff here?
						//user_login();
					}
				} else {
					$('userformsubmit' + action).disabled = false;
					var err = node_value(xml.getElementsByTagName('err')[0]);
					// signup
					if ( err == 109 ) {
						usernotice_set('Do you wish to <a href="#" onclick="$(\'' + action + 'captchaimg\').reload();return false;">reload</a> the image?', action);
						$(action + 'captchafield').focus();
					} else if ( err == 201 ) {
						usernotice_set('Please enter a valid email address into a field below.', action);
						$(action + 'emailfield').focus();
					} else if ( err == 203 ) {
						usernotice_set('Do you, perhaps, wish to <a href="/login.php" onclick="return userform_show(\'login\');">login</a> or <a href="/reset.php" onclick="return userform_show(\'reset\');">recover your password</a> instead?', action);
						$(action + 'emailfield').focus();
					} else if ( err == 205 ) {
						userform_hide(action);
					} else if ( err == 207 ) {
						userform_hide(action);
					} else if ( err == 209 ) {
						usernotice_set('Please initiate <a href="/reset.php" onclick="return userform_show(\'reset\');">Password Recovery</a> procedure.', action);
					} else if ( err == 211 ) { // password/signup/login
						usernotice_set('Please enter a password into a field below.', action);
						$(action + 'passwordfield').focus();
					} else if ( err == 213 ) {
						usernotice_set('Please enter a new password <strong><em>twice</em></strong> into the fields below.', action);
						$(action + 'newpasswordfield').value = '';
						$(action + 'newpasswordfield2').value = '';
						$(action + 'newpasswordfield').focus();
					} else if ( err == 215 ) {
						if ( $('userformsignup') ) {
							usernotice_set('Do you, perhaps, wish to <a href="/signup.php" onclick="return userform_show(\'signup\');">signup for a new account</a> instead?', action);
						} else {
							usernotice_set('The email you have provided was not found.', action);
						}
						$(action + 'emailfield').focus();
					} else if ( err == 217 ) { // reset (password)
						if ( $('userformsignup') ) {
							usernotice_set('Do you, perhaps, wish to <a href="/signup.php" onclick="return userform_show(\'signup\');">signup for a new account</a> or <a href="/reset.php" onclick="return userform_show(\'reset\');">recover your password</a> instead?', action);
						} else {
							usernotice_set('Do you, perhaps, wish to <a href="/reset.php" onclick="return userform_show(\'reset\');">recover your password</a> instead?', action);
						}
						$(action + 'emailfield').focus();
					} else if ( err == 219 ) { // info
						usernotice_set('Please enter your name. First name would suffice, but last name would be nice too.', action);
						$(action + 'firstnamefield').focus();
					}
				}
			},
			onFailure: function() { $('userformsubmit' + action).disabled = false; bar_error_show('API call failed, something went wrong...') }
		}
	);
	return false;
}

function usernotice_set(txt, sufix, cls) {
	if ( !sufix ) sufix = '';
	if ( !cls ) cls = 'api_error';
	$('usernotice' + sufix).innerHTML = txt;
	$('usernotice' + sufix).className = cls;
}



function goallist_expand(obj) {
	obj.className = ( obj.className == 'hidden' ? 'rowdescript' : 'hidden' );
	return false;
}

function progress_bar_set(newval, progressID) {
	var title = roundNumber(newval, 2).toString() + '%';
	var perc  = Math.round(parseFloat(newval)).toString() + '%';
	if ( typeof(progressID) == 'undefined' ) {
		$('goalprogress').title = title;
		$('goalprogressbar').style.width = parseInt(newval, 10) + '%';
	} else {
		$('critprogress' + progressID).title = title;
		$('critprogressbar' + progressID).style.width = parseInt(newval, 10) + '%';
	}
}


function next_step_set(nextstep) {
	//alert('"' + nextstep + '"');
	if ( nextstep && nextstep != '' ) {
		// view goal page
		if ( $('goalviewnextsteplabel') ) {
			$('goalviewnextsteplabel').innerHTML = nextstep;
		}
		// all pages
		if ( $('goalnextstep') ) {
			$('goalnextstep').show();
			$('goalnextsteplabel').innerHTML = nextstep;
		}
	} else {
		if ( $('goalnextstep') ) {
			$('goalnextstep').hide();
		}
	}
}

function evalcalc_simple(objIdent) {
	var obj = $('evalcalct' + objIdent);
	if ( objIdent == 'crit' ) {
		//
	} else if ( objIdent == 'alt' ) {
		//
	}
	// extract the values
	var ecCrit = parseInt($('evalcalccrit').value, 10);
	var ecAlt  = parseInt($('evalcalcalt' ).value, 10);
	// calculate
	var r =
		ecCrit * ( ecCrit - 1 ) / 2 + // criteria comparisons
		ecCrit * ( ecAlt * ( ecAlt - 1 ) / 2 ) // alternative comparisons (for every criteria)
	;
	var r2 =
		ecCrit * ( ecCrit - 1 ) / 2 + // criteria comparisons
		ecCrit // alternative values (for every criteria)
	;
	// build message
	var txt = r2 + ' to ' + r + ' comparisons';
	// populate
	$('evalcalcresult').innerHTML = txt;
	$('evalcalcresult').title = 'If all criteria are measurable, then it can be as low as ' + r2 + ' comparisons.';
}

function evalcalc_advanced(objIdent) {
	var obj = $('evalcalc' + objIdent);
	if ( objIdent == 'quant' ) {
		if ( obj.value > $('evalcalctcrit').value ) {
			$('evalcalctcrit').value = obj.value;
		}
	} else if ( objIdent == 'tcrit' ) {
		if ( obj.value < $('evalcalcquant').value ) {
			$('evalcalcquant').value = obj.value;
		}
	} else if ( objIdent == 'alt' ) {
		if ( !$('evalcalcadv').checked ) {
			return evalcalc_simple(objIdent);
		}
	}
	// extract the values
	var ecQuant = parseInt($('evalcalcquant').value, 10);
	var ecCrit  = parseInt($('evalcalctcrit').value, 10);
	var ecAlt   = parseInt($('evalcalcalt'  ).value, 10);
	// calculate
	var r =
		( ecCrit * ( ecCrit - 1 ) / 2 ) + // criteria comparisons
		( ecAlt * ( ecAlt - 1 ) / 2 ) * ( ecCrit - ecQuant ) + // alternative comparisons (for every criteria)
		ecQuant // alternative values (for every criteria)
	;
	// build message
	var txt = r + ' comparisons';
	// populate
	$('evalcalcresult').innerHTML = txt;
}

function evalcalc_advanced_switch(show) {
	toggleClass('evalcalcsimple'  , 'brick', 'hidden');
	toggleClass('evalcalcadvanced', 'brick', 'hidden');
	if ( show ) {
		evalcalc_advanced(this, 'quant');
	} else {
		evalcalc_simple(this, 'crit');
	}
}


function roundNumber(num, dec) {
	if ( typeof dec != 'number' ) dec = 2; // zero is not logical, since then Math.round() would be used
	return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}


function api_handle(xml) {
	var r = xml.responseXML.documentElement;
	var res = r.getElementsByTagName('res');
	var msg = r.getElementsByTagName('msg');
	var err = r.getElementsByTagName('err');
	if ( res.length > 0 && msg.length > 0 ) {
		if ( node_value(res[0]) == 0 ) {
			if ( err.length == 1 ) {
				var m = "Error " + node_value(err[0]) + ": " + node_value(msg[0]);
			} else {
				var m = node_value(msg[0]);
			}
			bar_error_show(m);
		} else {
			bar_result_show(node_value(msg[0]));
		}
	}
	return r;
}

function node_value(node) {
	return ( node.textContent !== undefined ? node.textContent : ( node.firstChild === null ? node.nodeValue : node.firstChild.nodeValue ) );
}


function bar_result_show(txt, sec) {
	if ( !sec ) sec = 6;
	if ( !txt ) txt = 'Changes Saved.';
	txt = nl2br(txt) + ' &nbsp; <sup><a href="#" onclick="Effect.BlindUp(\'bar_result\');">[-]</a></sup>';
	$('bar_result_text').innerHTML = txt;
	// cleanup other
	$('bar_error').hide();
	$('bar_loader').hide();
	// show this one
	Effect.BlindDown('bar_result');
	// set to get removed in x seconds
	window.setTimeout(function() { Effect.BlindUp('bar_result'); }, sec * 1000);
}


function bar_error_show(txt, sec) {
	if ( !sec ) sec = 6;
	if ( !txt ) txt = 'Changes Saved.';
	txt = nl2br(txt) + '<sup><a href="#" onclick="Effect.BlindUp(\'bar_error\');">[-]</a></sup>';
	$('bar_error_text').innerHTML = txt;
	// cleanup other
	$('bar_result').hide();
	$('bar_loader').hide();
	// show this one
	Effect.BlindDown('bar_error');
	// set to get removed in x seconds
	window.setTimeout(function() { Effect.BlindUp('bar_error'); }, sec * 1000);
}


function bar_loader_show(txt, sec) {
	if ( !sec ) sec = 15;
	if ( !txt ) {
		$('bar_loader_text').innerHTML = nl2br('Loading...');
	} else {
		$('bar_loader_text').innerHTML = nl2br(txt);
	}
	// cleanup other
	$('bar_error').hide();
	$('bar_result').hide();
	// show this one
	Effect.BlindDown('bar_loader');
	// set to get removed in x seconds
	window.setTimeout(function() { Effect.BlindUp('bar_loader'); }, sec * 1000);
}

// ASSIGN WINDOW.ONLOAD FUNCTIONS HERE
function onload_hookup(func) {
	var oldonload = window.onload;
	if ( typeof window.onload != 'function' ) {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

// ASSIGN WINDOW.ONUNLOAD FUNCTIONS HERE
function onunload_hookup(func) {
	var oldonunload = window.onunload;
	if ( typeof window.onunload != 'function' ) {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

function toggleClass(id, cls1, cls2) {
	$(id).className = ( $(id).className == cls1 ? cls2 : cls1 );
}

function bible(obj, firstLetter) {
	var out = '';
	for ( var i in obj ) {
		if ( !firstLetter || i.substr(0, 1) == firstLetter )
			out += i + ' = ' + obj[i] + '\n';
	}
	alert(out);
	if ( ( ta = document.getElementById('bible') ) == null ) {
		ta = document.createElement('textarea');
		ta.setAttribute('cols', 80);
		ta.setAttribute('rows', 25);
		ta.setAttribute('id', 'bible');
		document.body.appendChild(ta);
	}
	ta.value = out;
}


var so = { };
function amchart(obj) {
	var minFlash = '8';
	// first check all object properties
	if ( typeof(obj) != 'object' ) obj = { };
	if ( !obj.type ) obj.type = 'pie';
	if ( obj.type != 'column' || obj.type != 'line' || obj.type != 'pie' || obj.type != 'xy' ) obj.type = 'pie';
	if ( !obj.obj ) obj.obj = 'chartobj';
	if ( !obj.id ) obj.id = 'chartobj';
	if ( !obj.url ) obj.url = '/chart.php?goal=' + goal.code;
	if ( !obj.width ) obj.width = '100%';
	if ( !obj.height ) obj.height = '400';
	if ( !obj.bgcolor ) obj.bgcolor = '#FFFFFF';
	if ( !obj.title ) obj.title = document.domain;
	// now set new amChart
	so[obj.id] = swfobject.embedSWF(
		'/amcharts/am' + obj.type + '.swf', // movie url
		obj.obj, // div=>obj id
		obj.width, // width
		obj.height, // height
		minFlash, // minimum flash version
		false, // exress install
		// vars
		{
			path: '/amcharts/',
			settings_file: encodeURIComponent('/amcharts/am' + obj.type + '_settings.xml?rand=' + b64_encode(Math.random().toString())),
			//data_file: encodeURIComponent('/amcharts/am' + obj.type + '_data.xml'),
			data_file: encodeURIComponent(obj.url + '&t=' + obj.type),
			loading_settings: 'LOADING GOAL SETTINGS',
			loading_data: 'LOADING DECISION DATA',
			preloader_color: '#999999',
			additional_chart_settings: '<settings><labels><label lid="0"><text><![CDATA[<b>' + obj.title + '</b>]]></text></label></labels></settings>'
		},
		// params
		{
			bgcolor: obj.bgcolor,
			quality: 'high',
			wmode: 'transparent'
		},
		// attribs
		{
			id: obj.id
		}
	);
}

/*
function amchart_config(id, data, append) {
	if ( !append ) {
		so[id].addVariable('chart_settings', encodeURIComponent(data)); // "data in CSV or XML format"
	} else {
		so[id].addVariable('additional_chart_settings', encodeURIComponent(data)); // "<settings>...</settings>"
	}
}

function amchart_update(id, data) {
	so[id].addVariable('chart_data', encodeURIComponent(data)); // "<settings>...</settings>"
}
*/

function chart_event_url(type, id) {
	//alert('type: ' + type + '\nid: ' + id);
	if ( type == 'c' ) { // if clicked on chart's criteria
		// must b cid=0 result
		// offer other results then?
		alert(goal.crits[id]['name']);
	} else if ( type == 'a' ) { // if clicked on chart's alternatives
		// check if we should redirect to it's url
		if ( goal.useurls > 0 && goal.alts[id]['url'] && goal.alts[id]['url'] != '' ) {
			window.location.href = goal.alts[id]['url'];
		} else {
			// any other conditions/cases here?
		}
	}
}




var b64_encode = base64_encode;
var b64_decode = base64_decode;



/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

