
function isIE() {
    return (navigator.userAgent.toLowerCase().indexOf('msie') != -1);
}

function display_post_result(target, url, params) {
    var form = document.createElement("form");
    form.name = "poster";
    form.method = "POST";
    form.action = url;
    form.target = target;
    document.body.appendChild(form);
    for (var i in params) {
        var input = document.createElement("input");
        input.type = "hidden";
        input.name = i;
        input.value = params[i];
        form.appendChild(input);
    }
    form.submit();
    document.body.removeChild(form);
}

function display_gm_page(target, url, code) {
    display_post_result(target, "/tools/gm", { "url": url, "code": code })
}

function display_filled_form(target, url, fields, extraCode) {
    var code = ""
    for (var i in fields) {
        code += "e = document.getElementsByName('" + i + "');\n";
        code += "if (e[0].type == 'radio') {\n";
        code += "    for (var i = 0; i < e.length; i++) {\n";
        code += "        if (e[i].value == decodeURIComponent(\"" + encodeURIComponent(fields[i]) + "\")) { e[i].checked = true; }\n";
        code += "    }\n"
        code += "} else {\n";
        code += "    e[0].value = decodeURIComponent(\"" + encodeURIComponent(fields[i]) + "\");\n"
        code += "}\n"
    }
    if (extraCode != null) {
        code += extraCode;
    }
    display_gm_page(target, url, code);
}

function random_subset(num, list) {
    var subset = [];
    while (subset.length < num && list.length > 0) {
        var randomIndex = Math.floor(list.length * Math.random());
        subset[subset.length] = list.splice(randomIndex, 1);
    }
    return subset;
}

function geodata(names, max, def, callback) {
    var url = "/tools/geodata";
    if (typeof(names) == "string") {
        names = [names];
    }
    var params = "names=" + encodeURIComponent(names.join(","));
    params += "&max=" + max;
    params += "&default=" + def;

    new Ajax.Request(url, { method: 'post',
                            parameters: params,
                            asynchronous: true,
                            onSuccess: function(req) {
                                var output = eval("(" + req.responseText + ")");
                                callback(output);
                            }
                          });
}

function switchPageMode(displayed) {
    if (displayed) {
        switchPageToActionMode();
    } else {
        switchPageToViewMode();
    }
}

function switchPageToActionMode() {
    $('act_button').className = 'actBtnClicked';
	$('click_arrow').hide();
    sideLinksDisabledMode();
}

function switchPageToViewMode() {
    $('act_button').className = 'actBtn';
    if (!getActButtonAvailable()) {
        $('act_button').hide();
    }
    sideLinksNormalMode();
}

function adjustHeight() {
	if (!$('talking_points')) {
		return;
	}

	var dims = getWindowDimensions();
	var contentHeight = $('talking_points').offsetHeight;
	contentHeight += $('talking_points_footer') ? ($('talking_points_footer').offsetHeight) : 0;
	var tpHeight = (dims.windowHeight - (280 + ($('achievement') ? 50 : 0)));
	if (tpHeight > contentHeight  + 30) {
		tpHeight = contentHeight  + 30;
	}
	if (tpHeight < 50) {
		tpHeight = 50;
	}


	$('talking_points_container').style.height = tpHeight + "px";
}

function initPage() {

    if ($('talking_points')) {
        if ($('talking_points_container')) {
            $('talking_points_container').insertBefore($('talking_points'), $('talking_points_container').firstChild);
        }
    }

    if ($('action_title')) {
        $('action_title_container').appendChild($('action_title'));
    }


    if (typeof(actButton) != 'undefined') {
        $('act_button').show();
        $('click_arrow').show();
		setTimeout(function() { $('click_arrow').hide(); }, 12000);
    } else {
        setActButtonAvailable(false);
    }
    if ($('page_body')) {
        $('page_body_container').appendChild($('page_body'));
    }

	adjustHeight();
}

function notifyOperation(operationName, extra) {
  window.setTimeout(function() {
	  try {
		  var timestamp = Math.round(new Date().getTime()/1000);
		  var actionID = '';
		  var userSource = '';
		  var guid = null;		  
		  if (getUserSource && getUserSource()) {
		    userSource = getUserSource();
		  }
		  if (getGUID && getGUID()) {
		  	guid = getGUID();
		  }
		  if (getActionID && getActionID()) {
		    actionID = getActionID();
		  }
		  var url = "/notify.gif?op=" + encodeURIComponent(operationName) + "&mid=" + encodeURIComponent(actionID) + "&ts=" + timestamp + "&s=" + encodeURIComponent(userSource);
		  if (typeof(Automate) != 'undefined' && Automate.testMode) {
			  if ((typeof(Collactive) != 'undefined') && (typeof(Collactive.CSAUtils) != 'undefined') && Collactive.CSAUtils.hasCSA()) {
				var assistant = "assistant=1";
			  } else {
				var assistant = "assistant=0";
			  }
			  url = "/notify.gif?autotest=1&"+assistant+"&op=" + encodeURIComponent(operationName) + "&mid=" + encodeURIComponent(actionID) + "&ts=" + timestamp + "&s=" + encodeURIComponent(userSource);
		  }
		  if (guid) {
		  	url += "&guid=" + guid;
		  }
		  if (extra != null) {
		    url = url + extra;
		  }
	      new Ajax.Request(url, { method:'get', onSuccess: function(){}, onFailure: function(){} });
	  } catch (e) {
	  }
  }, 100);
}

var actButtonAvailable = true;

function setActButtonAvailable(available) {
    actButtonAvailable = available;
}

function getActButtonAvailable() {
    return actButtonAvailable;
}

var actButtonClicked = false;

function setActButtonClicked(clicked) {
    actButtonClicked = clicked;
}

function getActButtonClicked() {
    return actButtonClicked;
}

function displayCompletionMessage(success, subtitle, description, contentHTML, cancelLabel, postActionLabel, postActionFunc, cancelFunc) {
	if (typeof(Automate) != 'undefined') {
		if (success) {
			Automate.done();
		} else {
			Automate.error();
		}
	}
    setActButtonAvailable(!success);
    getWizardUI().gotoStepByName('action_completed');
	wizardUI.displayContent(subtitle, description, null, contentHTML,
	                        [[postActionLabel, function() {
                                                    wizardUI.hide();
                                				    postActionFunc();
                                               }]],
                            [[cancelLabel, (typeof(cancelFunc) != 'undefined') ? function() { wizardUI.hide(); cancelFunc(); }  : function() { wizardUI.hide(); }]]
                            );
}

function findElementPosition(elem) {
	var leftPos = 0;
	var topPos = 0;
	while (elem != null) {

		leftPos += elem.offsetLeft;
		topPos += elem.offsetTop;
		elem = elem.offsetParent;
	}
	return [ leftPos, topPos];
}

var showActionDescriptionTimer = null;
var hideActionDescriptionMouseOut = null;
var hideActionDescriptionTimer = null;
var actionDescriptionInitialized = false;

function startShowingActionDescription() {
     if (showActionDescriptionTimer != null) {
        return;
     }
     if (typeof(getActionDescription) == 'undefined') {
        return;
     }
     if ($('act_button').attributes['class'].value.indexOf('Clicked') >= 1) {
        return;
     }
    showActionDescriptionTimer = setTimeout(showActionDescription, 500);
}
function showActionDescription() {
     if (showActionDescriptionTimer) {
        clearTimeout(showActionDescriptionTimer);
        showActionDescriptionTimer = null;
     }
     if ($('act_button').attributes['class'].value.indexOf('Clicked') >= 1) {
        return;
     }

     if (hideActionDescriptionTimer) {
        clearTimeout(hideActionDescriptionTimer);
        hideActionDescriptionTimer = null;
     }
     if (!actionDescriptionInitialized) {
	     $('act_button_description_content').innerHTML = getActionDescription();
	     Event.observe($('act_button_description'), 'mouseover', showActionDescription, false);
	     Event.observe($('act_button_description'), 'mouseout', startHidingActionDescription, false);
		 actionDescriptionInitialized = true;
     }
     $('act_button_description').show();
     if (hideActionDescriptionMouseOut == null) {
       hideActionDescriptionMouseOut = Event.observe($('act_button'), 'mouseout', startHidingActionDescription, false);
     }
}

function startHidingActionDescription() {
     if (showActionDescriptionTimer) {
        clearTimeout(showActionDescriptionTimer);
        showActionDescriptionTimer = null;
     }
     if (hideActionDescriptionMouseOut != null) {
        Event.stopObserving($('act_button'), 'mouseout', hideActionDescriptionMouseOut, false);
        hideActionDescriptionMouseOut = null;
     }
    if (hideActionDescriptionTimer) {
        clearTimeout(hideActionDescriptionTimer);
        hideActionDescriptionTimer = null;
    }

    hideActionDescriptionTimer = setTimeout(hideActionDescription, 300);
}

function hideActionDescription() {
     $('act_button_description').hide();
}

var sideLinks = [];
function defineSideLink(id) {
    sideLinks.push(id);
}

function getSideLinks() {
    return sideLinks;
}

function sideLinksNormalMode() {
    $('side_links').show();
    for (var i = 0; i < sideLinks.length; i++) {
        var button = $(sideLinks[i]);
        button.className = 'genBtn';
        for (var j = 0; j < button.childNodes.length; j++) {
            if (button.childNodes[j].tagName == 'A') {
                button.childNodes[j].innerHTML = button.getAttribute('title');
            }
        }
    }
}

function sideLinksSmallMode() {
    $('side_links').show();
    for (var i = 0; i < sideLinks.length; i++) {
        var button = $(sideLinks[i]);
        for (var j = 0; j < button.childNodes.length; j++) {
            if (button.childNodes[j].tagName == 'A') {
                button.childNodes[j].innerHTML = '';
            }
        }
        button.className = 'genBtnSml';
    }
}

function sideLinksDisabledMode() {
    for (var i = 0; i < sideLinks.length; i++) {
        var button = $(sideLinks[i]);
        button.className = 'genBtnDisabled';
    }
}

var assistantInit = false;
function setAssistantInit() {
    assistantInit = true;
}

function getAssistantInit() {
    return assistantInit;
}

function waitForAssistantInit(callback) {
    if (assistantInit) {
        callback();
    } else {
        setTimeout(function() { waitForAssistantInit(callback) }, 100);
    }
}

function displayPreAction(siteLogo, siteLongName, learnMoreLink, actionTitle, actionDescription, actionImage, siteDescription, actionCallback) {
    getWizardUI().gotoStepByName('description');
    var m = [];
    m[m.length] = '<div style="margin: 20px">';
    m[m.length] = '  <div>';
    m[m.length] = '    <table>';
    m[m.length] = '      <tr>';
    m[m.length] = '        <td valign="middle">';
    m[m.length] = actionImage;
    m[m.length] = '        </td>';
    m[m.length] = '        <td valign="middle" style="padding-left: 15px; line-height: 18px; font-size: 14px">';
    m[m.length] =            actionDescription;
    m[m.length] = '        </td>';
    m[m.length] = '      </tr>';
    m[m.length] = '    </table>';
    m[m.length] = '  </div>';
    m[m.length] = '  <div style="border: 2px solid #aec1ca; padding: 5px; margin-top: 15px; margin-left: 30px; width: 530px" >';
    m[m.length] = '    <table>';
    m[m.length] = '      <tr>';
    m[m.length] = '        <td valign="top">';
    m[m.length] = '          <img src="/images/apage/wizard/info.gif" width="22" height="22" style="margin-right: 5px">';
    m[m.length] = '        </td>';
    m[m.length] = '        <td valign="top" style="font-size: 12px; line-height: 16px">';
    m[m.length] = '          <div style="font-weight: bold; margin-bottom: 10px; font-size: 13px">What is ' + siteLongName + '?</div>';
    m[m.length] =            siteDescription;
    m[m.length] = '          <br><br><a target="_blank" href="' + learnMoreLink + '">Learn more about ' + siteLongName + '</a>';
    m[m.length] = '        </td>';
    m[m.length] = '      </tr>';
    m[m.length] = '    </table>';
    m[m.length] = '  </div>';
    m[m.length] = '</div>';

    getWizardUI().displayContent(actionTitle, null, siteLogo, m.join("\n"),
                            [["Next", function() { notifyOperation("pre_action_continue"); actionCallback(); } ]],
                            [["Cancel", Collactive.bind(this, function() {
                                  getWizardUI().hide();
                            })]]
                            );

}

function displayJoinNetworkAction(group_name, group_logo, landingPageUrl, description, actionCallback) {
    getWizardUI().gotoStepByName('join');

    var m = [];
    m[m.length] = '  <div>';
    m[m.length] = '    <table>';
    m[m.length] = '      <tr>';
    m[m.length] = '        <td valign="middle" style="padding-left: 15px; padding-top: 15px; line-height: 18px; font-size: 14px">';
	m[m.length] = '           Dear friend,<br>';
	m[m.length] = '           You\'ve reached a campaign of ' + group_name + '.';
	m[m.length] = '           We appreciate your support.<br>';
	m[m.length] = '           In order to take part in our Internet campaigns, please join us by clicking the link below.';
    m[m.length] = '        </td>';
    m[m.length] = '      </tr>';
    m[m.length] = '    </table>';
    m[m.length] = '  </div>';
    m[m.length] = '<div style="margin: 30px 20px">';
    m[m.length] = '  <div style="border: 2px solid #aec1ca; padding: 5px; margin-top: 15px; width: 530px" >';
    m[m.length] = '    <table>';
    m[m.length] = '      <tr>';
    m[m.length] = '        <td valign="middle" align="left" width="100%">';
    m[m.length] = '          <div style="font-weight: bold; margin-bottom: 10px; font-size: 13px">About ' + group_name + '</div>';
    m[m.length] = '        </td>';
    m[m.length] = '        <td valign="top" width="94" align="right"> ';
    m[m.length] = '          <img src="' + group_logo + '" width="94" height="35" style="margin-right: 5px">';
    m[m.length] = '        </td>';
    m[m.length] = '      </tr>';
    m[m.length] = '      <tr>';
    m[m.length] = '        <td valign="top" colspan="2" style="padding-top: 5px; font-size: 12px; line-height: 16px">';
	m[m.length] = description;
	m[m.length] = '        </td>';
    m[m.length] = '      </tr>';
    m[m.length] = '    </table>';
    m[m.length] = '  </div>';
    m[m.length] = '</div>';
    m[m.length] = '<div style="margin: 20px; font-weight: bold; font-size: 20px">';
    m[m.length] = '    <a onclick="notifyOperation(' + "'" + "join_us_action" + "'" + ')" href="' + landingPageUrl + '">Join us!</a>';
    m[m.length] = '</div>';

    getWizardUI().displayContent(null, null, null, m.join("\n"),
                            [["Next", function() { notifyOperation("join_us_action"); actionCallback(); } ]],
                            [["Cancel", Collactive.bind(this, function() {
                                  getWizardUI().hide();
                            })]]
                            );

}

// Action page starts here.
function actionWrapper(func) {
	return function() {
		var args = Array.from(arguments);
        waitForAssistantInit(function() {
        		try {
        			func.apply(this, args);
        		} catch (e) {
        			if (e == "CSARequired") {
						displayJoinNetworkAction(getGroupName(), getGroupLogo(),
						getGroupLandingPage(), getGroupDescription(), function(){document.location = getGroupLandingPage();});
        			}
        		}
            });
	}
}


function getWindowDimensions() {
    var windowWidth = (typeof(window.innerWidth) == 'number') ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth);
    var windowHeight = (typeof(window.innerHeight) == 'number') ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight);
    var pageXOffset = (typeof(window.pageXOffset) == 'number') ? window.pageXOffset : (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
    var pageYOffset = (typeof(window.pageYOffset) == 'number') ? window.pageYOffset : (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
    return { windowWidth: windowWidth,  windowHeight: windowHeight,  pageXOffset: pageXOffset, pageYOffset: pageYOffset };
}


function showEmailForm() {
    $('email_details').show();
    $('email_sending').hide();
    $('email_sent').hide();
    if ($('edit_region')) {
        $('edit_region').hide();
    }
    $('email_form').show();
    $('email_recipients').focus();
}

function hideEmailForm() {
    $('email_form').hide();
    if ($('edit_region')) {
        $('edit_region').show();
    }
}

function showEmailSent() {
    $('email_sending').hide();
    $('email_sent').show();
    setTimeout(hideEmailForm, 4000);
}
var class0,v;
function chg_cls(obj) { //change navigation class on mouseover and mouseout
	with (obj) {
		v = attributes['class'].value;
		if (v.indexOf('On') < 1) {
			class0 = v;
			attributes['class'].value += 'Over';
			onmouseout = function () { if (attributes['class'].value.indexOf('Over') != -1) { attributes['class'].value = class0; } }
		}
	}
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

Event.observe(window, "beforeunload", function(e) {

        if ((typeof(actButton) == 'undefined') || getActButtonClicked()) {
			notifyOperation('before_unload');
            return true;
        } else {
			notifyOperation('no_click_unload');
			if (false) {
				if (typeof(startAction) != 'undefined') {
					startAction(true);
				}
	            Event.stop(e);
				var msg = "Please click CANCEL to go back and participate.";
	            e.returnValue = msg;
			}
            return true;
        }
     }, true);


