<?php
/**
* @Copyright Copyright (C) 2010 Brent Laminack
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
**/
defined('_JEXEC') or die('Restricted Access');
define('DEFAULT_FIELD_SIZE', 25);
define('MIN_FIELD_SIZE', 10);
?>
	<script type="text/javascript" src="<?php echo JURI::base(); ?>modules/mod_mailchimp2/ajax.js"> </script>

	<script type="text/javascript">
	// Global Ajax request
	var MCajaxReq = new MCAjaxRequest();

	// Add a new email address on the server using Ajax
	function getInterestGroup(inputgroup){
		var iginputs = document.getElementById(inputgroup);
		if(!iginputs){
			return('');
		}
		var group_id = iginputs.getElementsByTagName('legend');
		ig_values = 'mcig_' + group_id[0].title + ','
		if(iginputs){
			if(iginputs.getElementsByTagName('input').length){
				var inputs = iginputs.getElementsByTagName('input'); 	// radio or checkbox
			} else {
				var inputs = iginputs.getElementsByTagName('option'); 	// select list
			}
			if(inputs){
				for (var i=0; i < inputs.length; i++) {
 					// checked for radio or checkbox, selected for select list
					if (inputs[i].checked || inputs[i].selected) { 
					      ig_values = ig_values + inputs[i].value + ",";
	      				}
				}
			}
		}
		return(ig_values);
	}	// end of getInterestGroup

	function getInterestGroups(){
		var retstring;
		retstring = '';
		for(i=1; i<10; i++){
			var groupname;
			groupname = 'mciginputs' + i;
			retstring = retstring + getInterestGroup(groupname);
		}
		return(retstring);
	} // end of getInterestGroups

	function addEmailAddress() {

		// check email address for validity against big, nasty regular expression
		var regex = /^[\w\.-_\+]+@[\w-]+(\.\w{2,6})+$/;

		if(!regex.test(document.getElementById("email").value)){
			document.getElementById("status").innerHTML = "Invalid email address";
			return;
		}

		// Disable the Add button and set the status to busy
		document.getElementById("add").disabled = true;
		document.getElementById("status").innerHTML = "Adding...";

		// Send the new email entry and our module id data as an Ajax request
		postvars = "ajax=true" + "&mid=<?php echo $module->id;?>" + "&email=" + document.getElementById("email").value;
		var mergeVarInputs = document.getElementById('mcmergevars');
		mvinputs = mergeVarInputs.getElementsByTagName('input');
		maxj = mvinputs.length;
		for(j=0; j < maxj; j++){
			if(mvinputs[j].value){
				postvars = postvars + "&" + mvinputs[j].getAttribute('name') + 
					"=" + mvinputs[j].value;
			}

		}
	
		var i_groups;	
		i_groups = getInterestGroups();
		if(i_groups.length){
			postvars = postvars + "&ig=" + i_groups;
		}
		MCajaxReq.send("POST", "<?php echo JURI::base(); ?>modules/mod_mailchimp2/send_to_mc.php", handleRequest, "application/x-www-form-urlencoded; charset=UTF-8", postvars);

	}	// end of addEmailAddress

	// Handle the Ajax request
	function handleRequest() {
		if (MCajaxReq.getReadyState() == 4 && MCajaxReq.getStatus() == 200) {
			// Confirm the addition of the email entry
			document.getElementById("status").innerHTML = MCajaxReq.getResponseText();
			document.getElementById("add").disabled = false;
			document.getElementById("email").value = "";
			var mvinputs = document.getElementById('mcmergevars');	// clear mergevars
			if(mvinputs.getElementsByTagName('input').length){
				var inputs = mvinputs.getElementsByTagName('input');
				if(inputs){
					for (var i=0; i < inputs.length; i++) {	
						inputs[i].value = '';		
					}
				}
			}
			/* clear checkboxes and radios */
			var iginputs = document.getElementById('mciginputs');
			ig_values = "";
			if(iginputs){
				if(iginputs.getElementsByTagName('input').length){
					var inputs = iginputs.getElementsByTagName('input'); 	// radio or checkbox
				} else {
					var inputs = iginputs.getElementsByTagName('option'); 	// select list
				}
				if(inputs){
					for (var i=0; i < inputs.length; i++) {
	 					// checked for radio or checkbox, selected for select list
						if (inputs[i].checked || inputs[i].selected) { 
							inputs[i].checked = false;
		      				}
					}
				}
			}
		}
	}

	</script>
<?php 
	require_once('MCAPI.class.php');
	require_once('mod_mailchimp2_helper.php');
	$api = new MCAPI($params->get('mc_api_key'));
	$list_id = ($params->get('mc_unique_id'));
	$list_return = $api->lists();
	if($api->errorCode){
		echo "can't find lists: ";
		echo $api->errorMessage;
		echo " error code: ";
		echo $api->errorCode;
		exit;
	}
	$foundit=FALSE;
	$list_count = $list_return['total'];
	$lists = $list_return['data'];
	foreach($lists as $list){
		if($list['id'] == $list_id){
			$foundit=TRUE;
			break;
		}
	}
	if(!$foundit){
		echo ("couldn't find list with id $list_id");
		exit;
	}

	if($params->get('showlist')){
		echo $list['name'];
		echo '<br />';
	}

	$textsize = DEFAULT_FIELD_SIZE;
	if(is_numeric($params->get('textsize'))){
		$textsize = $params->get('textsize');
	}
	if($textsize < MIN_FIELD_SIZE){
		$textsize = MIN_FIELD_SIZE;
	}
		
?>
	<div id="status"></div>
	<form name="mailchimp2">
	e-mail address: <br />
	<input type="text" id="email" name="email" value="" size="<?php echo $textsize;?>"/><br />
	<?php if($params->get('askname')){ 
		$showname = "inline";
	} else {
		$showname = "none";
	} ?>
	<div id="mcmergevars" style="display: <?php echo $showname;?>">
	<?php   
    		$mergevars = $api->listMergeVars($list_id);
		// show extra signup fields
		// returns name req tag
		foreach($mergevars as $mergevar){
			if($mergevar['tag'] == 'EMAIL') {
				continue;
			} else {
				// prompt
				$spanclass="notreq";
				if($mergevar['req']){
					$spanclass="req";
				}
				echo '<span class="' . $spanclass . '">' . $mergevar['name'] . ": </span><br />\n";
				echo '<input class="mergevars" type="text" name="' . $mergevar['tag'] . '" ';
				echo 'size="' . $textsize . '"';
				echo "/><br />\n";
			}
		}
		echo '</div>';
		if($params->get('askinterest')){
			// show interest areas
 			//* @returnf string name Name for the Interest groups
			//* @returnf string form_field Gives the type of interest group: checkbox,radio,select
			//* @returnf array groups Array of the group names
			$int_groups = $api->listInterestGroupings($list_id);
			$i = 1;
			foreach($int_groups as $int_group){
				$groups = $int_group['groups'];
				echo '<fieldset class="mciginputs" id="mciginputs' . $i . '">';
				$i++;
				echo '<legend title="' . $int_group['id'] . '">' . $int_group['name'] . '</legend>';
				switch ($int_group['form_field']) {
					case "checkboxes":	
						foreach($groups as $group){
							echo '<input type="checkbox" name="ig" value="' . $group['name'] . '" />'. $group['name'] . "<br />\n";
						}
						break;
					case "radio":
						foreach($groups as $group){
							echo '<input type="radio" name="ig" value="' . $group['name'] . '" />' . $group['name'] . "<br />\n";
						}
						break;
					case "dropdown":
						echo '<select name="ig" id="mciginputs" >';
						foreach($groups as $group){
							echo '<option>' . $group['name'] . "</option>\n";
						}
						echo '</select><br />';
			
						break;
					default:
						echo "can't happen";
						break;
					} // end of case
					echo '</fieldset>';
				} // end of foreach
			}

	?>
	<input type="button" id="add" value="Add" onClick="addEmailAddress();" /></form><br />
