<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs 
    title="MailChimp Signup Form" 
    category="communication" category2="tools"
    title_url="http://www.mailchimp.com/plugins/opensocial/" 
    author="MailChimp API Team"
    author_email="api@mailchimp.com"
    author_location="Atlanta, GA, USA"
    thumbnail="http://www.mailchimp.com/plugins/download/os_thumb.png"
    screenshot="http://www.mailchimp.com/plugins/download/os_screenshot.jpg"
    description="MailChimp Signup Form for your product marketing, band newsletter, or any other email newsletters."
    >
    <Icon>http://www.mailchimp.com/favicon.ico</Icon>
    <Require feature="opensocial-0.7"/>
    <Require feature="dynamic-height"/>
    <Require feature="views"/>
  </ModulePrefs>
  <Content type="html" view="canvas" height="600px">
    <![CDATA[
<style type="text/css">
*{margin:0;padding:0;}
.container { overflow:auto; height:590; }
#header{width:100%;float:left;background:#fecb66;}
.header_content {width:615px;margin:0 auto;}
.header_content h2{float:left;height:60px;font-size:12px;width:300px;}
.header_content p{float:right;background:#fff;color:#666;text-align:right;line-height:1.5em;padding:4px 10px;font-size:14px;margin:14px 0 0 0;border:1px solid #e8d2b8;}
a{color:#0033CC;}
h1, h2, p, form{
	border:0px; 
	margin:0px; 
	padding:0px;
}	
div.main{
	margin:0 auto; 
	width:650px;
	}
span#welcome_box{
	color:#333333;
	margin-top:2px;
	float:right;
}

div.box{
	border:solid 1px #e8d2b8;
	background:#f7f3e5;
	padding:15px;
	color:#333333;
	margin-top:15px;
	float:left;
	width:620px;
	font-family: helvetica, arial, serif;
}
div.box h1 {
	font-size:18px;
	margin-bottom:15px;
	border-bottom:1px solid #e8d2b8;
	width:615px;
	padding-bottom:5px;
	float:left;clear:both;
	color:#404040;
	text-transform: capitalize;
	font-family: helvetica, arial, serif;
}
div.box h2 {
	font-size:14px;
	color:#333;
	margin-bottom:15px;
	border-bottom:1px solid #e8d2b8;
	width:615px;
	padding-bottom:5px;
	float:left;clear:both;
}
div.box input.input-text{
	border:1px solid #ccc;
	color:#666666;
	width:220px;
	background:#fff;
	font-size:13px;
	height:24px;
}
div.box input.input-text-nosz{
	border:1px solid #ccc;
	color:#666666;
	background:#fff;
	font-size:13px;
	height:24px;
	padding:2px 0;
}

div.box i{font-style:italic;font-size:11px;color:#777;}

div.box textarea.heading {
	border:1px solid #ccc;
	color:#666666;
	width:360px;
	background:#fff;
	font-size:14px;
	clear:none;
	height:70px;
	padding:0; margin:0;
}

div.box input.check{
	border:none;
	color:#666666;
	width:20px;
	font-size:14px;
	height:22px;
}
div.box select{
	border:1px solid #ccc;
	color:#666666;
	width:360px;
	background:#fff;
	font-size:14px;
	height:22px;
}
div.box label{
	display:block;
	margin-bottom:10px;
	color:#777;
	font-size:12px;
	width:100%;
	clear:both;
}
div.box label span{
	display:block;
	float:left;
	padding-right:6px;
	width:160px;
	text-align:right;
	font-weight:bold;
	padding-top:4px;
}
div.box label span.right { 
	display:block;
	float:left;
	padding-right:6px;
	width:250px;
	text-align:left;
	font-weight:normal;
	padding-top:4px;
}
.green{
	background:#336699;
	padding:2px 10px;
	border:1px solid #3b6e22;
	height:24px; 
	line-height:24px;
	color:#FFFFFF;
	font-size:14px;
	font-weight:bold;
	display:inline-block;
	text-decoration:none;
	clear:left;
	float:left;
}
.panel{ float:left;margin:5px 0 5px 0; clear:both; display:none;}
.success { font-weight: bolder; color: green; }
.error { font-weight: bolder; color: red; }
.container { overflow:auto; height:590; }
.status_msg{ height:20px; float:left; clear:both;}
</style>
<div class="container">

<div id="header">
	<div class="header_content" style="width:650px;">
		<h2><img src="http://mailchimp.com/opensocial_logo.gif"></h2>
		<span id="welcome_box"><p style="font-size:13px;font-family:arial;">Welcome!</p></span>
	</div>
</div>
<div class="main" id="main">
<div id='panel_no' class="panel">
<div id="no_msg" class="box">
<span id="goaway_msg" class="status_msg" style="float:left;margin-top:20px;margin-left:15px;"> 
<span class="error">Loading... note that this page is only for the app owner!</span>
</span>
</div>
</div>
<!-- LOGIN PANEL -->
<div id='panel_0' class="panel">
<div class="box">
<h1>Enter Your MailChimp Login Info</h1>
<label><span>Login:</span>
	<input type="text" id="user" value="" class="input-text" style="margin-top:2px;">
</label>
<label><span>Password:</span>
	<input type="password" id="pass" value="" class="input-text" style="margin-top:2px;">
</label>
<a href="javascript:void(0);" onClick="checkLogin();" class="green">Login</a>
</div>
<a href="http://www.mailchimp.com/tryit.phtml" target="blank">Don't have an account? Signup for Free!</a>
<span id="status_msg" class="status_msg" style="float:left;margin-top:20px;margin-left:15px;"> </span>
</div>

<!-- PICK LIST PANEL -->
<div id='panel_1' class="panel"></div>

<!-- STYLING & FIELDS PANEL -->
<div id='panel_2' class="panel">
<div class="box">
<!-- <h1 id="selected_header"></h1><a name="configure">   </a> -->
<h1>2. Select the Merge Fields you would like to display:</h1>

<div id='mergevars'></div>

<div id='interestgroups'></div>
</div>
<div class="box">
<h1>3. Customize:</h1>
<label><span style="text-align:left;">Header content:</span>
	<textarea name="header_content" id="header_content" class="heading" style="width:615px;"> <h2>Sign up for Test List</h2> </textarea>
	<br/>
	<i style="font-size:11px;">You can fill this with your own Text, HTML markup (including image links), or Nothing!</i>
</label>
<label style="padding-top:10px;"><span style="text-align:left;width:135px;padding:2px 0 0 0;">Submit Button text:</span>
	<input type="text" id="submit_text" name="submit_text" style="width:615px;" value="Subscribe" class="input-text-nosz" style="padding:0;margin:0;"/><br/>
	<i style="font-size:11px;float:left;padding-top:3px;padding-bottom:10px;">You can fill this with your own Text, HTML markup (including image links), or Nothing!</i>
</label>
</div>

<div class="box">
<h1>4. Styling:</h1>
<label><span>Turned On?</span>
	<input type="checkbox" id="custom_style" name="custom_style" checked class="check" style="margin-top:2px;"/>
</label>


<label style="padding-top:5px;"><span>Border Width:</span>
	  <input type="text" id="form_border_width" name="form_border_width" size="3" maxlength="3" value="1" class="input-text-nosz"/> px<br/>
<span> </span><span class="right"><i style="padding-bottom:10px;float:left;margin-top:-2px;">Set to 0 for no border, do not enter <strong>px</strong>!</i></span>
</label>

<label><span>Border Color:</span>
	#<input type="text" id="form_border_color" name="form_border_color" size="7" maxlength="6" value="ccc" class="input-text-nosz"/><br/>
<span> </span><span class="right"><i style="padding-bottom:10px;float:left;margin-top:-2px;">do not enter initial <strong>#</strong></i></span>
</label>

<label><span>Text Color:</span>
	#<input type="text" id="form_text_color" name="form_text_color" size="7" maxlength="6" value="666666" class="input-text-nosz"/><br/>
<span> </span><span class="right"><i style="padding-bottom:10px;float:left;margin-top:-2px;">do not enter initial <strong>#</strong></i></span>
</label>

<label><span>Background Color:</span>
	#<input type="text" id="form_background" name="form_background" size="7" maxlength="6" value="ffffcc" class="input-text-nosz"/><br/>
<span> </span><span class="right"><i style="padding-bottom:10px;float:left;margin-top:-2px;">do not enter initial <strong>#</strong></i></span>
</label>



</div>
<br />
<p style="float:left;"><a href="javascript:void(0);" onClick="saveSettings();" class="green" style="text-align:center;margin-top:15px;margin-bottom:20px;width:200px;">Save All Settings</a></p>
<br/>
<span id="status_msg2" style="float:left;margin-top:20px;margin-left:15px;"> </span>
</div>

</div>
<script type="text/javascript">
var MC_CFG_KEY = "mailchimp_config";
var os = opensocial.Container.get();
var viewer;
var owner;
var baseUrl = "http://api.mailchimp.com/1.1/?output=json";

var mccfg = {};

var maxPanels = 3;
var step = 0;

var curMsg = 0;

gadgets.window.adjustHeight();

init();
function init() {

    try {
        document.getElementById('panel_no').style.display='none';
	    req = os.newDataRequest();
	    req.add( req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER), 'owner' );
	    req.add( req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER), 'viewer' );
	    req.add( req.newFetchPersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, MC_CFG_KEY), 'mccfg');
	    req.send(initResp);
     } catch(e){
        document.getElementById('panel_no').style.display='block';
        document.getElementById('panel_no').innerHTML = '<span class="error">Sorry, either we encountered an error loading or you are not the owner of this App. Please try reloading...</span>';
        log(e);
     }
}

function log(str){
    try{
        console.log(str);
    } catch(e){}
}

function dispNo(){
    document.getElementById('panel_no').style.display='block';
    document.getElementById('no_msg').innerHTML = '<span class="error"><p>Sorry, either we encountered an error loading or you are not the owner of this App.</p><br/><p><ul><li>If you are the Owner, please try reloading...</li><li>If you are not the owner, there is nothing here for you.</p></span>';
}

function checkPerm(){
	if (viewer == null || owner == null || viewer.getId() != owner.getId()){
		document.getElementById('panel_0').innerHTML = '';
		document.getElementById('panel_1').innerHTML = '';
		document.getElementById('panel_2').innerHTML = '';
		return false;
	}
	return true;
}

function initResp(obj) {

    viewer = obj.get('viewer').getData();
    owner = obj.get('owner').getData();
    if (!checkPerm()){ return; }
    cfg = obj.get('mccfg');//.getData();

    //this should be *plenty* sufficient, but it doesn't work consistently across platforms
    if (cfg.hadError() || cfg.getData() == new Object()){
        mccfg = {};
    } else {
        init_x = cfg.getData();
        //log( dumpObj(obj.get('mccfg').getData(),'mccfg','•',0) );
        //this try/catch block brought to you by myspace's failure to implement gadgets.util
       try{
            try {
                mccfg = gadgets.json.parse( gadgets.util.unescapeString(init_x[owner.getId()][MC_CFG_KEY]) );
            } catch(e){
                mccfg = gadgets.json.parse( unescape(init_x[viewer.getId()][MC_CFG_KEY]) );
            }
        }catch(e){
            mccfg = {};
        }
    }

	if (mccfg.apikey == undefined){
		step = 0;
		dispPanel(step);
	} else {
		step = 2;
        document.getElementById('welcome_box').innerHTML = '<p style="font-size:13px;font-family:arial;">Logged in as <b>'+mccfg.username+'</b> | <a href="javascript:void(0);" onclick="logout();">Log Out</a></p>';
		dispPanel(1);
		dispPanel(2);		
		dispMergeVars();
		dispInterestGroups();
	}
}
function logout(){
    document.getElementById('welcome_box').innerHTML = '<p style="font-size:13px;font-family:arial;">Welcome!</p>';
    document.getElementById('panel_0').style.display='block';
    document.getElementById('panel_1').style.display='none';
    document.getElementById('panel_2').style.display='none';
    try{
        document.getElementById('status_msg').innerHTML = ' ';
    } catch (e){}
    try{
        document.getElementById('status_msg2').innerHTML = ' ';
    } catch (e){}        
}
function dispMsg(msg, append){
    curMsg++;
    try {
	    document.getElementById('status_msg').style.display = 'block';
	    if (append){
		    document.getElementById('status_msg').innerHTML += '<br/>'+msg;
	    } else {
		    document.getElementById('status_msg').innerHTML = msg;
	    }
	    //curMsg lets us "cancel" hiding the message...
	    setTimeout("if (curMsg=="+curMsg+"){ try { document.getElementById('status_msg').innerHTML = ' ';}catch(e){} }",5000);
	} catch(e){}
	try{
	    document.getElementById('status_msg2').style.display = 'block';
	    if (append){
		    document.getElementById('status_msg2').innerHTML += '<br/>'+msg;
	    } else {
		    document.getElementById('status_msg2').innerHTML = msg;
	    }
	    //curMsg lets us "cancel" hiding the message...
	    setTimeout("if (curMsg=="+curMsg+"){ try { document.getElementById('status_msg2').innerHTML = ' ';}catch(e){} }",5000);
	}catch(e){}
}

function dispPanel(num){
	if (!checkPerm()){ return; }
	document.getElementById('panel_'+num).style.display = 'block';
	switch(num){
		case 0: break;
		case 1: loadLists(); break;
		case 2: showStyling();
		break;
	}
	for(i=(num+1);i<maxPanels;i++){
		document.getElementById('panel_'+i).style.display = 'none';
	}
}

function saveSettings() { 
    if (!checkPerm()){ return; }
    //need to collect pieces and save them...
    // apikey, listId, styling sections, merge_vars + options, interest groups + options
    // more?
    data = {};
    data.username = mccfg.username;
    data.apikey = mccfg.apikey;
    data.listId = mccfg.listId;
    data.listName = mccfg.listName;
    data.header_content = document.getElementById('header_content').value;
    data.submit_text = document.getElementById('submit_text').value;
    data.custom_style = document.getElementById('custom_style').value;
    data.form_border_width = document.getElementById('form_border_width').value;
    data.form_border_color = document.getElementById('form_border_color').value;
    data.form_text_color = document.getElementById('form_text_color').value;
    data.form_background = document.getElementById('form_background').value;


    if (mccfg.merge_vars!=undefined){
    for(i=0;i<mccfg.merge_vars.length;i++){
        if (!mccfg.merge_vars[i].req){
            if (document.getElementById('mv_'+mccfg.merge_vars[i].tag).checked){
                mccfg.merge_vars[i].disp = true;
            } else {
                mccfg.merge_vars[i].disp = false;
            }
        } else {
            mccfg.merge_vars[i].disp = true;
        }
    }
    }
    data.merge_vars = mccfg.merge_vars;
    if (mccfg.interest_groups == undefined || mccfg.interest_groups.groups == undefined){
        data.show_igs = false;
    } else {
        data.show_igs = document.getElementById('show_igs').checked;
    }
    data.interest_groups = mccfg.interest_groups;
    
    //dispMsg( dumpObj(data,'data','•',0),false);
    req = os.newDataRequest();
    //this try/catch block brought to you by myspace's failure to implement gadgetsg.util
    try {
        req.add( req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, MC_CFG_KEY, gadgets.util.escape(gadgets.json.stringify(data)) ) , 'mccfg');
    } catch(e){
        req.add( req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, MC_CFG_KEY, escape(gadgets.json.stringify(data)) ) , 'mccfg');
    }
    req.send(cb_saveSettings);
        
}
function cb_saveSettings(obj){
    if (obj.get('mccfg').hadError()){
        dispMsg('<span class="error">Uh-oh, something went wrong while saving. Please try again!</span>', false);
        return;
    }
    req.add( req.newFetchPersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, MC_CFG_KEY), 'mccfg');
    req.send(cb_cb_saveSettings);
}

function cb_cb_saveSettings(obj){
    cfg = obj.get('mccfg').getData();
    if (cfg == undefined || !cfg){
        dispMsg('<span class="error">Uh-oh, something went wrong while saving. Please try again!</span>', false);
        document.getElementById('panel_2').style.border = "6px solid red";
    } else {
        //this try/catch block brought to you by myspace's failure to implement gadgets.util
        try {
            mccfg = gadgets.json.parse(gadgets.util.unescapeString(cfg[viewer.getId()][MC_CFG_KEY]));
        } catch(e){
            mccfg = gadgets.json.parse( unescape(cfg[viewer.getId()][MC_CFG_KEY]) );
        }
        dispMsg('<span class="success">Saved!</span>', false);
        document.getElementById('main').style.background = "green";
    }
    var x = setTimeout("document.getElementById('main').style.background = '#FFF';",1000);
}


function checkLogin(){
	if (!checkPerm()){ return; }
	var url = baseUrl + "&method=login&username="+document.getElementById('user').value+"&password="+document.getElementById('pass').value;
	mccfg = {};
	mccfg.username = document.getElementById('user').value;
	var params = {}; 
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.RequestParameters.METHOD.POST;
    gadgets.io.makeRequest(url, cb_checkLogin, params);
}

function cb_checkLogin(resp){
    var obj = null;
    try {
        obj = gadgets.json.parse(resp.text);
    } catch(e){

        dispMsg('<span class="error">An Unknown Error Occurred. Please try again later.</span>',false);
        //dispMsg( dumpObj(resp,'data','•',0),false);
        mccfg = {};
        mccfg.apikey = '';
        step = 0;
        dispPanel(step);
        return;
    }
    if (obj.code == undefined){
        //mccfg = { 'apikey': obj };
        document.getElementById('welcome_box').innerHTML = '<p style="font-size:13px;font-family:arial;">Logged in as <b>'+mccfg.username+'</b> | <a href="javascript:void(0);" onclick="logout();">Log Out</a></p>';
        mccfg.apikey = obj;
        step = 1;
        dispPanel(step);
    } else {
        dispMsg('<span class="error">' + obj.error + '<br/></span>',false);
        mccfg = {};
        mccfg.apikey = '';
        step = 0;
        dispPanel(step);
    }
}

function loadLists(){
	if (!checkPerm()){ return; }
	var url = baseUrl + "&method=lists&apikey="+mccfg.apikey;
	var params = {}; 
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.RequestParameters.METHOD.POST;
        gadgets.io.makeRequest(url, cb_loadLists, params);
}
function cb_loadLists(resp){
    try {
        //dispMsg( dumpObj(resp,'data','•',0),false);
        obj = gadgets.json.parse(resp.text);
    } catch(e){
        dispMsg('<span class="error">An Unknown Error Occurred while loading your lists. Please try again later.</span>',false);
        mccfg.apikey = '';
        step = 0;
        dispPanel(step);
        return;
    }
    var disp = '<div class="box"><h1>1. Please select a list to use:</h1>';
    if (obj.length==0){
        disp += '<span class="error">ERROR: No lists found. Please login to the MailChimp site and setup at least 1 list!</span><br/>';
    } else {
        disp += '<select name="lists" id="lists" onchange="checkList();">';
        disp += '<option value=""> --- Please Select a List ---</option>';
        for(i=0;i<obj.length;i++){
            if (mccfg.listId == undefined){
                disp += '<option value="'+obj[i].id+'">'+obj[i].name+'</option>';
            } else {
                if (mccfg.listId == obj[i].id){
                    disp += '<option value="'+obj[i].id+'" selected>'+obj[i].name+'</option>';
                } else {
                    disp += '<option value="'+obj[i].id+'">'+obj[i].name+'</option>';
                }
            }
        }
        disp += '</select><br/><br/><p style="font-size:11px;"><i>Note: List will be loaded when you change the selection - doing this will erase your current config.</i></p>';
    }
    disp += '</div>';
    document.getElementById('panel_1').innerHTML = disp;
    document.getElementById('panel_0').style.display='none';
}

function checkList(){
	if (!checkPerm()){ return; }

	var sel = document.getElementById('lists');
	mccfg.listId = sel.options[sel.selectedIndex].value;
	if (mccfg.listId==''){ return; }
	mccfg.listName = sel.options[sel.selectedIndex].innerHTML;
	
	if (mccfg.listId == undefined || mccfg.listId==''){
		dispMsg('<span class="error">Please select a List before trying to continue.</span>');
	} else {
		step = 2;
		mccfg.header_content = null;
		mccfg.submit_text = null;
		mccfg.custom_style = null;
		mccfg.form_border_width = null;
		mccfg.form_border_color = null;
		mccfg.form_text_color = null;
		mccfg.form_background = null;
		mccfg.merge_vars = null;
		mccfg.interest_groups = null;
		document.getElementById('mergevars').innerHTML = '';
		document.getElementById('interestgroups').innerHTML = '';
		dispPanel(step);
		loadList();
	}
}

function showStyling(){
	if (!checkPerm()){ return; }
	// document.getElementById('selected_header').innerHTML = 'Selected MailChimp List: ' + mccfg.listName;
	var txt = '';
	if (mccfg.header_content != undefined){
		txt = mccfg.header_content;
    	document.getElementById('header_content').value = txt;
	}
	
	txt = 'Subscribe';
	if (mccfg.submit_text != undefined){
		txt = mccfg.submit_text;
	}
	document.getElementById('submit_text').value = txt;
	
	txt = true; // yes, I realize this is not actually "text"
	if (mccfg.custom_style != undefined){
		txt = mccfg.custom_style;
	}
	document.getElementById('custom_style').checked = txt;
	
	txt = "1";
	if (mccfg.form_border_width != undefined){
		txt = mccfg.form_border_width;
	}
	document.getElementById('form_border_width').value = txt;
	
	txt = "ccc";
	if (mccfg.form_border_color != undefined){
		txt = mccfg.form_border_color;
	}
	document.getElementById('form_border_color').value = txt;

	txt = "666666";
	if (mccfg.form_text_color != undefined){
		txt = mccfg.form_text_color;
	}
	document.getElementById('form_text_color').value = txt;

	txt = "ffffcc";
	if (mccfg.form_background != undefined){
		txt = mccfg.form_background;
	}
	document.getElementById('form_background').value = txt;
}

function loadList(){
	if (!checkPerm()){ return; }
	//this is actually the start of a chain of functions to load MergeVars, InterestGroups, and go ahead & save the settings...
	var url = baseUrl + "&method=listMergeVars&apikey="+mccfg.apikey+"&id="+mccfg.listId;
	var params = {}; 
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.RequestParameters.METHOD.POST;
        gadgets.io.makeRequest(url, cb_mergeVars, params);
	document.getElementById('panel_0').style.display='none';
	document.getElementById('panel_1').style.display='block';
}

function cb_mergeVars(resp){
	try {
		obj = gadgets.json.parse(resp.text);
	} catch(e){
		dispMsg('<span class="error">An Unknown Error Occurred while loading your Merge Vars. Please try again later.</span>',false);
		return;
	}
	//at this point, spin off the requests to get the Interest groups...
	var url = baseUrl + "&method=listInterestGroups&apikey="+mccfg.apikey+"&id="+mccfg.listId;
	var params = {}; 
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.RequestParameters.METHOD.POST;
        gadgets.io.makeRequest(url, cb_interestGroups, params);
	mccfg.merge_vars = obj;
    dispMergeVars();
}//cb_mergeVars

function dispMergeVars(){
	if (!checkPerm()){ return; }
        var disp = '';
        //ok, now setup the merge var display...
    if (mccfg.merge_vars.length==0){
        disp += '<span class="error">No Merge Vars found. Please try re-selecting a list.</span><br/>';
    } else {
        for(i=0;i<mccfg.merge_vars.length;i++){
            disp += '<label><span>'+mccfg.merge_vars[i].name+'</span>';
            if (mccfg.merge_vars[i].req){
                disp += '<span class="right"><em style="line-height:1.4em;color:#888;float:left;padding-bottom:13px;">*required</em></span><br/>';
            } else {
                var checked = " checked ";
                if (mccfg.merge_vars[i] != undefined){
                    if (mccfg.merge_vars[i].disp!=undefined && !mccfg.merge_vars[i].disp){
                        checked = "";
                    }
                }
                disp += '<input type="checkbox" id="mv_'+mccfg.merge_vars[i].tag+'" name="mv_'+mccfg.merge_vars[i].tag+'" '+checked+' class="check" style="margin-top:2px;">';
            }
            disp += '</label>';
        }
    }
    document.getElementById('mergevars').innerHTML = disp;
}//dispMergeVars

function cb_interestGroups(resp){
    try {
        obj = gadgets.json.parse(resp.text);
    } catch(e){
        dispMsg('<span class="error">An Unknown Error Occurred while loading your Interest Groups. Please try again later.</span>',false);
        apikey = '';
        step = 0;
        dispPanel(step);
        return;
    }
    mccfg.show_igs = true;
    mccfg.interest_groups = obj;
    dispInterestGroups();
    setTimeout('saveSettings();',500); //do this by default...
}

function dispInterestGroups(){
	if (!checkPerm()){ return; }
        var disp = '';
        //ok, now setup the interest group display...
	if (mccfg.interest_groups == undefined || mccfg.interest_groups.groups == undefined){
		disp += '<br /><h2>Interest Group display setup:</h2><p style="font-style:italic;font-size:11px;color:#777;">No Interest Groups found. If you would like to use them, you will need to set them up at MailChimp first.</p>';
	} else {
		var checked = " checked "; 
		if (mccfg.show_igs != undefined){
			if (!mccfg.show_igs){
				checked = "";
			}
		}
		disp += '<br/><h2>Interest Group display setup:</h2>';
		disp += '<label><span>Show?</span><input type="checkbox" id="show_igs" name="show_igs" '+checked+' class="check" style="margin-top:2px;"/></label>';
		disp += '<label><span>Name:</span><span class="right">'+mccfg.interest_groups.name+'</span></label><br/>';
		// disp += '<label><span>Input Type:</span><span class="right">'+mccfg.interest_groups.form_field+'</span></label><br/>';
		disp += '<label  style="float:left;padding-top:12px;"><span>Options:</span><span class="right">';
		for(i=0;i<mccfg.interest_groups.groups.length;i++){
			disp += '• '+mccfg.interest_groups.groups[i]+'<br/>';
		}
		disp += '</span></label>';
	}
	document.getElementById('interestgroups').innerHTML = disp;
}//cb_interestGroups


var MAX_DUMP_DEPTH = 10;

function dumpObj(obj, namer, indent, depth) {
      if (depth > MAX_DUMP_DEPTH) {
             return indent + namer + ": <Maximum Depth Reached>\n";
      }
      if (typeof obj == "object") {
             var child = null;
             var output = indent + namer + "<br>";
             indent += "   ";
             for (var item in obj)
             {
                   try {
                          child = obj[item];
                   } catch (e) {
                          child = "<Unable to Evaluate>";
                   }
                   if (typeof child == "object") {
                          output += dumpObj(child, item, indent, depth + 1);
                   } else {
                          output += indent + item + ": " + child + "<br>";
                   }
             }
             return output;
      } else {
             return obj;
      }
}
</script>


    ]]>
  </Content>

  <Content type="html" view="profile" height="325px">
    <![CDATA[
<style type="text/css">
.success { font-weight: bolder; color: green; }
.error { font-weight: bolder; color: red; }
#mc_signup_form{ padding: 10px; 
margin-top:0px; margin-left:5px;margin-right:5px;
margin-bottom:0px;
}
div.box{
	border:solid 1px #e8d2b8;
	background:#f7f3e5;
	padding:15px;
	color:#333333;
	margin-top:15px;
	float:left;
	width:95%;
	font-family: helvetica, arial, serif;
}
</style>
<div id='mc_signup_form'></div>
<script type="text/javascript">
var MC_CFG_KEY = "mailchimp_config";
var os = opensocial.Container.get();
var viewer;
var owner;

var baseUrl = "http://api.mailchimp.com/1.1/?output=json";

var mccfg = {};
init();
function init(){

    req = os.newDataRequest();
    req.add( req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER), 'viewer' );
    req.add( req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER), 'owner' );
    req.add( req.newFetchPersonAppDataRequest(opensocial.DataRequest.PersonId.OWNER, MC_CFG_KEY), 'mccfg');
    req.send(initResp);
}


function initResp(obj) {
    var disp = document.getElementById('mc_signup_form');
    viewer = obj.get('viewer').getData();
    owner = obj.get('owner').getData();
    cfg = obj.get('mccfg');
    
    //this should be *plenty* sufficient, but it doesn't work consistently across platforms
    if (cfg.hadError() || cfg.getData() == new Object()){
        mccfg = {};
    } else {
        init_x = cfg.getData();
        //log( dumpObj(obj.get('mccfg').getData(),'mccfg','•',0) );
        //this try/catch block brought to you by myspace's failure to implement gadgets.util
       try{
            try {
                mccfg = gadgets.json.parse( gadgets.util.unescapeString(init_x[owner.getId()][MC_CFG_KEY]) );
            } catch(e){
                mccfg = gadgets.json.parse( unescape(init_x[owner.getId()][MC_CFG_KEY]) );
            }
        }catch(e){
            mccfg = {};
        }
    }
    
    if (mccfg.apikey == undefined || mccfg.listId == undefined){
        var msg = '';
        if (viewer == null || owner == null || viewer.getId() != owner.getId()){
            msg = '<div class="box"><span class="error">The owner of this MailChimp Signup Form Application has not yet configured it. You may want to contact them about that.</span></div>';
        } else {
            msg = '<div class="box"><span class="error">You have installed this app, but not yet configured it!<br/>';
            msg += '<a href="javascript:gadgets.views.requestNavigateTo(new gadgets.views.View(\'canvas\'));">Please click here to do so.</a><br/>';
            msg += '</span></div>';
        }
        disp.innerHTML = msg;
        return;
     } 

    var names = '';
    var emails = '';
    try {
        var names = viewer.getField(opensocial.Person.Field.NAME).split(" ", 2);
        var emails = viewer.getField(opensocial.Person.Field.EMAILS);
    } catch(e){
        names = null;
        emails = null;
    }
    
    var form_style = '';
    disp.style.fontSize = '10px';
    disp.style.padding = '5px';
    disp.style.height = '100%';
    disp.style.overflow = 'auto';
    if (mccfg.custom_style){
        disp.style.border = mccfg.form_border_width+'px solid #'+mccfg.form_border_color;
        disp.style.background = '#'+mccfg.form_background;
        disp.style.color = '#'+mccfg.form_text_color;
    }   
    disp.innerHTML += mccfg.header_content;
    disp.innerHTML += '<span id="mc_info_msg"></span>';
    for(i=0;i<mccfg.merge_vars.length;i++){
        if (mccfg.merge_vars[i].req || mccfg.merge_vars[i].disp ){
            disp.innerHTML += mccfg.merge_vars[i].name + ':<br/>';
            var val = '';
            //try to fill in values, silently fail if we can't for whatever reason
            try{
                if (mccfg.merge_vars[i].tag=='FNAME'){
                    if (names[0] != undefined){
                        val = names[0];
                    }
                }
                if (mccfg.merge_vars[i].tag=='LNAME'){
                    if (names[1] != undefined){
                        val = names[1];
                    }
                }
                if (mccfg.merge_vars[i].tag=='EMAIL'){
                    val = emails[0].getField(opensocial.Email.Field.ADDRESS);
                }
            } catch(e){}
            
            disp.innerHTML += '<input type="text" size="20" value="'+val+'" name="mv_'+mccfg.merge_vars[i].tag+'" id="mv_'+mccfg.merge_vars[i].tag+'">';
            if (mccfg.merge_vars[i].req){
                disp.innerHTML += "*";
            }
            disp.innerHTML += '<br/>';
        }
    }
    disp.innerHTML += '<sup style="clear:both;">* = required field</sup><br/><br/>';
    if (mccfg.show_igs){
        if (mccfg.interest_groups.form_field=='checkbox'){
            for(i=0;i<mccfg.interest_groups.groups.length;i++){
                disp.innerHTML += '<input type="checkbox" id="interests['+mccfg.interest_groups.groups[i]+']">'+mccfg.interest_groups.groups[i]+'<br/>';
            }
        }else if (mccfg.interest_groups.form_field=='radio'){
            for(i=0;i<mccfg.interest_groups.groups.length;i++){
                disp.innerHTML += '<input type="radio" id="interests['+mccfg.interest_groups.groups[i]+']">'+mccfg.interest_groups.groups[i]+'<br/>';
            }
        }else if (mccfg.interest_groups.form_field=='select'){
            disp += '<select id="interests" name="interests">';
            for(i=0;i<mccfg.interest_groups.groups.length;i++){
                disp.innerHTML += '<option value="'+mccfg.interest_groups.groups[i]+'">'+mccfg.interest_groups.groups[i]+'</option>';
            }
            disp += '</select>';
        }
    }
    disp.innerHTML += '<div class="submit"><input type="submit" name="mc_signup" value="'+mccfg.submit_text+'" class="button" onclick="subscribe();"/></div>';
    
    gadgets.window.adjustHeight();
}

function subscribe(){

    var pars = '';
    for(i=0;i<mccfg.merge_vars.length;i++){
        if (mccfg.merge_vars[i].req || mccfg.merge_vars[i].disp ){
            if (mccfg.merge_vars[i].tag=='EMAIL'){
                pars += '&email_address='+document.getElementById('mv_'+mccfg.merge_vars[i].tag).value;
            } else {
                pars += '&merge_vars['+mccfg.merge_vars[i].tag+']='+document.getElementById('mv_'+mccfg.merge_vars[i].tag).value;
            }
        }
    }
    if (mccfg.show_igs){
        var interests = '';
        if (mccfg.interest_groups.form_field=='checkbox'){
            for(i=0;i<mccfg.interest_groups.groups.length;i++){
                if (document.getElementById( "interests["+mccfg.interest_groups.groups[i]+"]" ).checked ){
                    interests += mccfg.interest_groups.groups[i]+',';
                }
            }
        }else if (mccfg.interest_groups.form_field=='radio'){
            for(i=0;i<mccfg.interest_groups.groups.length;i++){
                if (document.getElementById( "interests["+mccfg.interest_groups.groups[i]+"]" ).checked ){
                    interests += mccfg.interest_groups.groups[i]+',';
                }
            }
        }else if (mccfg.interest_groups.form_field=='select'){
            var sel = document.getElementById('interests');
            interests += sel.options[sel.selectedIndex].value;
        }
        pars+='&merge_vars[INTERESTS]='+interests;
    }

    var url = baseUrl + "&method=listSubscribe&apikey="+mccfg.apikey+"&id="+mccfg.listId+pars;
//  alert(url);
    var params = {};
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.RequestParameters.METHOD.POST;
        gadgets.io.makeRequest(url, cb_subscribe, params);

}

function cb_subscribe(resp){
    var obj = null;
    try {
        obj = gadgets.json.parse(resp.text);
    } catch(e){
        document.getElementById('mc_info_msg').innerHTML = '<span class="error">An Unknown Error Occurred. Please try again later.</span><br/>'
        return;
    }
    if (obj.code == undefined){
        document.getElementById('mc_info_msg').innerHTML = '<span class="success">Successfully subscribed! Please check your email to confirm it!</span><br/>'
        return;
    } else {
        document.getElementById('mc_info_msg').innerHTML = '<span class="error">•'+obj.error+'</span><br/>'
        return;
    }
}
</script>

    ]]>
  </Content>

</Module>
