YAHOO.namespace("masi.util");
// define some extra info to store values available to all
YAHOO.masi.util.extra_info = {};
YAHOO.masi.util._object_list = {};
// mp is a shortcut to reduce the character count in html
function mp(event,method_string) {
	var my_array = method_string.split('___');
	var action = YAHOO.masi.util.get_object(my_array[0]);
	eval('var response = action.' + my_array[1] + '();');
	return response;
}
function mepa(unique_id,method_name) {
	var action = YAHOO.masi.util.get_object(unique_id);
	var new_arguments = '';
	for(var i=2;i<arguments.length;i++) {
		new_arguments += ",'" + arguments[i].replace(/\'/g, "\\'") + "'";
	}
	new_arguments = new_arguments.replace(/^,/,'');
	eval('var response = action.' + method_name + '(' + new_arguments + ')');
	// bberg
	if ( ! response ) {
		response = false;
	}
  	return response;
}
YAHOO.masi.util.method_passthrough = function(unique_id,method_name) {
	var action = YAHOO.masi.util.get_object(unique_id);
	var new_arguments = '';
	for(var i=2;i<arguments.length;i++) {
		new_arguments += ",'" + arguments[i].replace(/\'/g, "\\'") + "'";
	}
	new_arguments = new_arguments.replace(/^,/,'');
	eval('var response = action.' + method_name + '(' + new_arguments + ')');
	// bberg
	if ( ! response ) {
		response = false;
	}
	return response;
}
YAHOO.masi.util.get_object = function(id) {
  eval('var obj = YAHOO.masi.util._object_list.id_' + id);
	if ( obj ) {
		return obj;
	} else {
		return false;
	}
}
YAHOO.masi.util.add_object = function(id,obj) {
  eval('var obj = YAHOO.masi.util._object_list.id_' + id + ' = obj;');
}
YAHOO.masi.util.delete_object = function(id) {
  eval('delete YAHOO.masi.util._object_list.id_' + id);
}
// unique_id was pulled from the definitive guide, it should guarantee uniqueness within a page
YAHOO.masi.util.unique_id = (function() {
	// reserving the 1st set of numbers for objects that will stick around
	var id = 100;
	return function() {return id++; };
})()
YAHOO.masi.util.request_passthrough = function( config ) {
	//for ( var attribute in config ) {
	//	var value = config[attribute];
	//	YAHOO.masi.util.console_log("\t attribute ->" + attribute + "<- value ->" + value + "<-");
	//}

	/*
	config.param_string(optional)
	config.unique_id
	config.form_name(optional)
	config.callback_method
  config.error_callback(optional)
	config.request_method(optional, default: POST)
	config.url
  config.file_upload
	*/
	// create a function that is hardcoded to return the response text to the passed object's method
  var tmp_func;
  if(config.instance_variables)
  {
    var instance = new YAHOO.masi.util.instance_request(config);
    tmp_func = 'function( request ) { instance.handle_content( request.responseText );}';
  }
  else
  {
    tmp_func = 'function( request ) { var calling_obj = YAHOO.masi.util.get_object( "' + config.unique_id + '" ); calling_obj.' + config.callback_method + '( request.responseText );}';
  }
  eval('var my_function = ' + tmp_func);

	var callback = { success: my_function };
  if ( config.error_callback ) {
    var error_func = 'function( request ) { var calling_obj = YAHOO.masi.util.get_object( "' + config.unique_id + '" ); calling_obj.' + config.error_callback + '( request );}';
    eval('var error_function = ' + error_func);

    callback = {
      success: my_function,
      failure: error_function
    };
  }
  if ( config.file_upload ) {
//    var my_function = function( request ) {
//      var calling_obj = YAHOO.masi.util.get_object(config.unique_id);
//      var content = request.responseText;
//      alert(content);
//      content = content.substring(19,content.length-10);
//      content = content.replace(/&lt;/g,'<');
//      content = content.replace(/&gt;/g,'>');
//      content = content.replace(/<pre>/g,'');
//      content = content.replace(/<\/pre>/g,'');
//      alert(content);
//      eval('calling_obj.' + config.callback_method + '( content );');
//    }
    callback = { upload: my_function };
  }

	// allow a form to be submited by name, param_string can be added as well
  if ( config.form_name ) {
	  //    eval( 'var oForm = document.' + config.form_name );
	  //    YAHOO.util.Connect.setForm(oForm);
	  if ( config.file_upload ) {
		  YAHOO.util.Connect.setForm(config.form_name, true);
	  } else {
		  YAHOO.util.Connect.setForm(config.form_name);
	  }
  } else {
	  YAHOO.util.Connect.setForm();
  }

	// default to post, but allow GET
	var request_method = 'POST';
	if ( config.request_method ) {
		request_method = config.request_method;
	}
	var cObj = YAHOO.util.Connect.asyncRequest( request_method, config.url, callback, config.param_string );
}
YAHOO.masi.util.isValidEmail = function(sEmail) {
	var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
	var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
	var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
	var sQuotedPair = '\\x5c[\\x00-\\x7f]';
	var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
	var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
	var sDomain_ref = sAtom;
	var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
	var sWord = '(' + sAtom + '|' + sQuotedString + ')';
	var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
	var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
	var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
	var sValidEmail = '^' + sAddrSpec + '$'; // as whole string
	var reValidEmail = new RegExp( sValidEmail );
	if ( reValidEmail.test( sEmail ) ) {
		return true;
	}
	return false;
}
YAHOO.masi.util.escape_masi_delimited_data_transfer = function(value) {
	if ( value ) {
		value = value.replace(/=/g,"__\u2502_eq__");
		value = value.replace(/&/g,"__\u2502_amp__");
		value = value.replace(/</g,"__\u2502_lt__");
		value = value.replace(/>/g,"__\u2502_gt__");
	}
	return value;
}
YAHOO.masi.util.unescape_masi_delimited_data_transfer = function(value) {
	if ( value ) {
		value = value.replace(/__\u2502_eq__/g,'=');
		value = value.replace(/__\u2502_amp__/g,'&');
		value = value.replace(/__\u2502_lt__/g,'<');
		value = value.replace(/__\u2502_gt__/g,'>');
	}
	return value;
}
// ----------------------------------------
// background_process object, used for adcreator exports or any server side processing that may take some time
// THIS IS STILL IN DEVELOPMENT !!!
// process flow using a background_process object...
// 1. bp.start, send wrapped func call to the server
//		server returns a completion indicator
// 2. bp handles response and sets up the interval
//				LOOP
// 3. interval calls completion_interval, which submits a completion_check
// 4. completion handler does nothing, errors or completes
//				END LOOP
// ----------------------------------------
// our base object will automatically handle the unique_id and register the object
YAHOO.masi.util.base = function(unique_id,handler) {
	this.unique_id = unique_id;
	YAHOO.masi.util.add_object(this.unique_id,this);
}
// inherit from the base object to automatically handle unique_id and object registration
YAHOO.masi.util.background_process = function(unique_id,handler) {
	YAHOO.masi.util.base.call(this,unique_id);
	// initialize some internal variables
	this.handler = handler;
	this.inprocess = false;
	this.milliseconds = 3000;
	this.inprocess_id = 'inprocess';
	this.error_id = 'error';
	this.finished_id = 'finished';
}
// start, accepts a param string, form name and a file_upload indicator
// it adds process_func_in_background which will cause the real func to be wrapped
YAHOO.masi.util.background_process.prototype.start = function(params,form_name,file_upload) {
	if ( this.inprocess ) {
		return;
	}
	this.inprocess = true;
	this.set_inprocess();
	var param_string = 'process_func_in_background=1&update_session=1';
	if ( params ) {
		param_string += '&' + params;
	}
	var config = {
		url: this.handler,
		unique_id: this.unique_id,
		param_string: param_string,
		callback_method: 'start_handler'
	};
	if ( file_upload ) {
		config.file_upload = true;
	}

	if ( form_name ) {
		config.form_name = form_name;
	}
	YAHOO.masi.util.request_passthrough(config);
}
// start_handler, handles the wrapped func response
// it clears messages, creates the interval and calls set_inprocess
YAHOO.masi.util.background_process.prototype.start_handler = function(content) {
	//this.clear_messages();
	this.completion_indicator = content;
	this.completion_interval_id = window.setInterval( 'YAHOO.masi.util.method_passthrough("' + this.unique_id + '","completion_interval")', this.milliseconds );
	this.set_inprocess();
}
// completion_interval, called each time by the interval, submits a completion check to the server
YAHOO.masi.util.background_process.prototype.completion_interval = function() {
	var param_string = 'func=completion_check&completion_indicator=' + this.completion_indicator;
	var config = {
		url: this.handler,
		unique_id: this.unique_id,
		param_string: param_string,
		callback_method: 'completion_handler'
	};
	YAHOO.masi.util.request_passthrough(config);
}
// completion_handler, handles completion check response, may error, finish or do nothing
YAHOO.masi.util.background_process.prototype.completion_handler = function(content) {
	var i = content.indexOf(':');
	var status = content.substr(0,i);
	content = content.substr(i+1,content.length);
	if ( status == 'OK' ) {
		this.clear_interval();
		this.inprocess = false;
		this.set_complete(content);
		this.finish(content);
	} else if ( status == 'BP_REDIRECT' ) {
		this.clear_interval();
		this.inprocess = false;
		this.set_complete(content);
		window.location = this.handler + '?' + content;
	} else if ( status == 'REDIRECT' || status == 'INTERNAL_REDIRECT' ) {
		this.clear_interval();
		this.inprocess = false;
		this.set_complete(content);
		window.location = content;
	} else if ( status == 'ERROR' ) {
		this.inprocess = false;
		this.error(content);
	} else if ( content && document.getElementById(this.inprocess_id) ) {
		document.getElementById(this.inprocess_id).innerHTML = content;
	}
}
// set_inprocess, clears messages, changes cursor and displays 'inprocess' div if it exists
YAHOO.masi.util.background_process.prototype.set_inprocess = function(content) {
	document.body.style.cursor = "progress";
	if ( content && document.getElementById(this.inprocess_id) ) {
		document.getElementById(this.inprocess_id).innerHTML = content;
	}
	if ( document.getElementById(this.inprocess_id) ) {
    	document.getElementById(this.inprocess_id).style.display = 'block';
	}
}
// set_complete, clears messages and changes cursor to default
YAHOO.masi.util.background_process.prototype.set_complete = function(content) {
	this.clear_messages();
	document.body.style.cursor = "default";
}
// finish, after completion, this will perform the final work, set_complete would have been called prior to this
YAHOO.masi.util.background_process.prototype.finish = function(content) {
	this.clear_messages();
	if ( document.getElementById(this.finished_id) ) {
    	document.getElementById(this.finished_id).style.display = 'block';
	}
	window.location = content;
}
// error, calls set_complete, displays the indicated message and clears the interval
YAHOO.masi.util.background_process.prototype.error = function(message) {
	this.clear_interval();
	this.set_complete();
	if ( document.getElementById(this.error_id) ) {
		document.getElementById(this.error_id).innerHTML = message;
    	document.getElementById(this.error_id).style.display = 'block';
	}
}
// clear_messages, hides any messages that may be visible
YAHOO.masi.util.background_process.prototype.clear_messages = function() {
	if ( document.getElementById(this.finished_id) ) {
    	document.getElementById(this.finished_id).style.display = 'none';
		document.getElementById(this.finished_id).innerHTML = '';
	}
	if ( document.getElementById(this.inprocess_id) ) {
    	document.getElementById(this.inprocess_id).style.display = 'none';
		document.getElementById(this.inprocess_id).innerHTML = '';
	}
	if ( document.getElementById(this.error_id) ) {
    	document.getElementById(this.error_id).style.display = 'none';
		document.getElementById(this.error_id).innerHTML = '';
	}
}
// clear_interval, removes the interval and completion checking
YAHOO.masi.util.background_process.prototype.clear_interval = function() {
	window.clearInterval(this.completion_interval_id);
	delete this.completion_interval_id;
}
// simple string replace with object containing name/value attributes
// var account = {
//           name: 'test name',
//           phone_number: '309690xxxx'
//         };
// var row_section = '<li>__name__: __phone_number__"</li>";
// var my_list_content = YAHOO.masi.util.process_section(account,row_section);
YAHOO.masi.util.process_section = function(values_obj,section) {
	var tmp_string = section;
	for ( var attribute in values_obj ) {
		var value = values_obj[attribute];
		eval('tmp_string = tmp_string.replace(/__' + attribute + '__/g,value);');
	}
	return tmp_string;
}

YAHOO.masi.util.tab_controller = function(unique_id,obj_array,current_class,default_class,callback) {
	YAHOO.masi.util.base.call(this,unique_id);

	// make sure all required parameters exist
	if ( ! unique_id ) {
		//YAHOO.masi.util.console_log('No unique_id defined when constructing tab controller.');
	}
	if ( ! obj_array ) {
		//YAHOO.masi.util.console_log('No objects defined when constructing tab controller.');
	}
	if ( ! current_class ) {
		//YAHOO.masi.util.console_log('No current_class defined when constructing tab controller.');
	}
	if ( ! default_class ) {
		//YAHOO.masi.util.console_log('No default_class defined when constructing tab controller.');
	}

	this.current_index = 0;
	this.obj_array = obj_array;
	this.callback = callback;
	this.current_class = current_class;
	this.default_class = default_class;

	// error checking, make sure all element objects exist in the page
	for(var j=0;j<this.obj_array.length;j++){
		var item_obj = this.obj_array[j];
		item_obj.tab_obj = document.getElementById( item_obj.tab );
		item_obj.body_obj = document.getElementById( item_obj.body );

		if ( !item_obj.tab ) {
			//YAHOO.masi.util.console_log('Could not find tab at ' + item_obj.tab );
		}
		if ( ! item_obj.body ) {
			//YAHOO.masi.util.console_log('Could not find body at ' + item_obj.tab );
		}
	}
}
YAHOO.masi.util.tab_controller.prototype.show_tab = function(index) {
	if ( index || index == 0 ) {
		this.current_index = index;
	}

	for(var j=0;j<this.obj_array.length;j++){
		var item_obj = this.obj_array[j];

		if ( j == this.current_index ) {
			item_obj.body_obj.style.display = 'block';
			item_obj.tab_obj.className = this.current_class;
		} else {
			item_obj.body_obj.style.display = 'none';
			item_obj.tab_obj.className = this.default_class;
		}
	}

	// the callback provides the opportunity to operate on the option passed in
	if ( this.callback ) {
		eval('this.callback(index)');
	}
}
YAHOO.masi.util.toggle_checkbox = function(form_name,field_name,checkbox_name) {
	eval('var oField = document.' + form_name + '.' + field_name );
	eval('var oCheckbox = document.' + form_name + '.' + checkbox_name );
	if ( oCheckbox.checked ) {
		oField.value = 1;
	} else {
		oField.value = 0;
	}
}
YAHOO.masi.util.object_info_parser = function(content) {
	var info_object = {};
	if ( content ) {
		var elements_array = content.split("&");

		for (var i=0;i < elements_array.length;i++) {
			var el = false;
			var value_array = elements_array[i].split("=");
			var name = YAHOO.masi.util.unescape_masi_delimited_data_transfer(value_array[0]);
			var value = YAHOO.masi.util.unescape_masi_delimited_data_transfer(value_array[1]);
			// masi join table naming convention is a problem
			name = name.replace(/\./g,'_');
			eval('info_object.' + name + ' = value;');
		}
	}
	return info_object;
}

YAHOO.masi.util.instance_request = function(config)
{
  YAHOO.masi.util.base.call(this, YAHOO.masi.util.unique_id());
  this.config = config;
}
YAHOO.masi.util.instance_request.prototype = new YAHOO.masi.util.base();
YAHOO.masi.util.instance_request.prototype.constructor = YAHOO.masi.util.instance_request;
YAHOO.masi.util.instance_request.prototype.handle_content = function(content)
{
  var calling_obj = YAHOO.masi.util.get_object(this.config.unique_id);
  eval('calling_obj.' + this.config.callback_method + '( content, this.config.instance_variables );');
  this.destroy;
}
YAHOO.masi.util.instance_request.prototype.destroy = function()
{
  YAHOO.masi.util.delete_object(this.unique_id);
}
YAHOO.masi.util.console_log = function(message) {
	try {
		console.log(message);
	}
	catch(e) {
	}
}
YAHOO.masi.util.limit_string_cut_center = function(limit,substitute,name) {
		if ( name.length <= limit ) {
			return name;
		}
		var middle = name.length / 2;
		middle = parseInt(middle);
		var part_one = name.substr(0,middle);
		var part_two = name.substr(middle + 1);
		var c_to_remove = ( name.length - limit ) / 2;
		c_to_remove = parseInt(c_to_remove);
		name = part_one.substr(0,(part_one.length - c_to_remove) ) + substitute + part_two.substr(c_to_remove);
		return name;
}

