
var RecaptchaTemplates = {
	//pulled from the page, out of a template
    VertHtml: captchaHTML,
    VertCss: captchaCSS
};
var RecaptchaStr_en = {
    visual_challenge : "Get a visual challenge",
    audio_challenge : "Get an audio challenge",
    refresh_btn : "Get a new challenge",
    
    instructions_visual : "Type the two words:",
    instructions_audio : "Type the eight numbers:",

    help_btn : "Help",
    cant_hear_this : "Can't hear the sound?"
};

var RecaptchaLangMap = { 
  en: RecaptchaStr_en
};

var RecaptchaStr = RecaptchaStr_en;

var RecaptchaOptions;

var RecaptchaDefaultOptions = {
    tabindex: 0,
    theme: 'red',
    callback: null,
    lang: 'en'
};

var Recaptcha = {

    widget: null,
    
    timer_id: -1,

    style_set: false,

    theme: null,

    callback: null,

    type: 'image',

    helplink: 'http://recaptcha.net/popuphelp/',

    $: function(id) { 
      if (typeof(id) == "string") {
        return document.getElementById(id); 
      }
      else {
        return id;
      }
    },
    
    create: function(public_key, element, options) {
      if (Recaptcha.widget) {
        Recaptcha.destroy();
      }
      Recaptcha.widget = Recaptcha.$(element);
      RecaptchaOptions = options;
      Recaptcha.call_challenge(public_key);
    },

    destroy: function() {
      if (!Recaptcha.widget) {
        return;
      }
      if (Recaptcha.timer_id != -1) {
        clearInterval(Recaptcha.timer_id);
      }
      Recaptcha.timer_id = -1;
      Recaptcha.widget.innerHTML = "";
      Recaptcha.widget = null;
    },

    focus_response_field: function() {
      var $ = Recaptcha.$;
      var field = $('recaptcha_response_field_1');
      if (field) {
        field.focus();
      }
    },

    get_challenge: function() {
      if (typeof(RecaptchaState) == "undefined") {
        return null;
      }
      return RecaptchaState.challenge;
    },

    /*get_response: function() {
      var $ = Recaptcha.$;
      var field = $('recaptcha_response_field');
      if (!field) {
        return null;
      }
      return field.value;
    },*/

    call_challenge: function(public_key) {
      var protocol = window.location.protocol;
      if (protocol == 'https:') {
        var server = "api-secure.recaptcha.net";
      }
      else {
        var server = "api.recaptcha.net";
      }
      scriptURL = protocol + "//" + server + "/challenge?k=" + public_key + "&ajax=1";
      Recaptcha.add_script(scriptURL);
    },

    add_script: function(scriptURL) {
      var scriptTag = document.createElement("script");
      scriptTag.type = "text/javascript";
      scriptTag.src = scriptURL;
      Recaptcha.get_script_area().appendChild(scriptTag);
    },

    get_script_area: function() {
      var parentElement = document.getElementsByTagName("head");
      if (!parentElement || parentElement.length < 1) {
        parentElement = document.body;
      }
      else {
        parentElement = parentElement[0];
      }
      return parentElement;
    },

    challenge_callback: function() {
      var element = Recaptcha.widget;
      Recaptcha.reset_timer ();

      var comb_opt = RecaptchaDefaultOptions;
      RecaptchaOptions = RecaptchaOptions || {};

      for (var p in RecaptchaOptions) {
        comb_opt[p] = RecaptchaOptions[p];
      }
      RecaptchaOptions = comb_opt;

      var lang = RecaptchaLangMap[RecaptchaOptions.lang];
      if (typeof(lang) != "undefined") {
        RecaptchaStr = lang;
      }

      /* Try to avoid back/forward cache problems */
      // firefox
      if (window.addEventListener) {
        window.addEventListener('unload', function(e){ Recaptcha.destroy(); }, false );
      }
      // IE
      if (navigator.userAgent.indexOf("MSIE") > 0 && window.attachEvent) {
        window.attachEvent('onbeforeunload', function () {
          // I think this may be causing some errors -- it seems
          // that sometimes IE isn't submitting the form fully
          // This may be breaking the back button functionality
          // :-(
          //Recaptcha.destroy();
        });
      }
      // safari
      if (navigator.userAgent.indexOf("KHTML") > 0) {
        var iframe = document.createElement('iframe');
        iframe.src = "about:blank";
        iframe.style.height = "0px";
        iframe.style.width = "0px";
        iframe.style.visibility = "hidden";
        iframe.style.border = "none";
        var textNode = document.createTextNode("This frame prevents back/forward cache problems in Safari.");
        iframe.appendChild(textNode);
        document.body.appendChild(iframe);
      }   
      
//       if (Recaptcha.is_gecko17_or_less()) {
//         // for some reason, we need this in gecko 1.7 (firefox 1.0)
//         window.setTimeout(Recaptcha.finish_widget, 0);
//       } else {
        Recaptcha.finish_widget();
//       }
    },

    set_style: function(css) {
      // We only allow the style to be set once, because IE behaves
      // poorly otherwise.  Same goes for Recaptcha.theme.
      if (Recaptcha.style_set) {
        return;
      }
      Recaptcha.style_set = true;
      var styleTag = document.createElement("style");
      styleTag.type = "text/css";
      if (styleTag.styleSheet) { // IE only
        if (navigator.appVersion.indexOf("MSIE 5") != -1) { // IE 5 crashes if we add a style tag to the DOM
          document.write("<style type='text/css'>" + css + "</style>");
        }
        else {
          styleTag.styleSheet.cssText = css;
        }
      }
      else {
        var textNode = document.createTextNode(css);
        styleTag.appendChild(textNode);
      }
      Recaptcha.get_script_area().appendChild(styleTag);
    },

    finish_widget: function() {
      var $ = Recaptcha.$;
      var $_ = RecaptchaStr;
      var $ST = RecaptchaState;
      var $OPT = RecaptchaOptions;

      var theme = $OPT.theme;
      switch (theme) {
      case 'red': case 'white': case 'blackglass': case 'clean':
        break;
      default:
        theme = 'red';
        break;
      }
      if (!Recaptcha.theme) {
        Recaptcha.theme = theme;
      }
      

      var server_no_slash = $ST.server;
      if (server_no_slash[server_no_slash.length - 1] == "/")
      server_no_slash = server_no_slash.substring (0, server_no_slash.length - 1);
      var IMGROOT = server_no_slash + "/img/" + Recaptcha.theme
      
      var css = RecaptchaTemplates.VertCss;
      var html = RecaptchaTemplates.VertHtml;
      var img_format = "gif";
      
      css = css.replace (/IMGROOT/g, IMGROOT);
      
      Recaptcha.set_style(css);
      Recaptcha.widget.innerHTML = "<div id='recaptcha_area'>" + html + "</div>";

      
      //$('recaptcha_table').className = "recaptchatable " + "recaptcha_theme_" + Recaptcha.theme
      $('recaptcha_image').src = $ST.server + 'image?c=' + $ST.challenge;
      $('recaptcha_challenge_field').value = $ST.challenge;
      //$('recaptcha_response_field').tabIndex = $OPT.tabindex;
      
      
      /*$('recaptcha_reload_btn').href = "javascript:Recaptcha.reload ('r');";
      $('recaptcha_reload_btn').title = $_.refresh_btn;
      $('recaptcha_reload').alt = $_.refresh_btn;
      
      $('recaptcha_switch_audio_btn').href = "javascript:Recaptcha.switch_type('audio');";
      $('recaptcha_switch_audio').title = $_.audio_challenge;
      $('recaptcha_switch_audio').alt = $_.audio_challenge;
      
      $('recaptcha_switch_img_btn').href = "javascript:Recaptcha.switch_type('image');";
      $('recaptcha_switch_img').title = $_.visual_challenge;
      $('recaptcha_switch_img').alt = $_.visual_challenge;
      
      $('recaptcha_whatsthis_btn').href = Recaptcha.helplink;
      $('recaptcha_whatsthis_btn').target = "_blank";
      $('recaptcha_whatsthis').title = $_.help_btn;
      $('recaptcha_whatsthis').alt = $_.help_btn;
      */
      
      /*$('recaptcha_whatsthis_btn').onclick = function () {
        Recaptcha.showhelp();
        return false; 
      };*/
      
      Recaptcha.set_instructions();
      
      if ($ST.error_message) {
        if ($("recaptcha_instructions")) {
          $("recaptcha_instructions").innerHTML = $ST.error_message;
        }
      }
      
      /*$('recaptcha_reload').src = IMGROOT + "/refresh." + img_format;
      $('recaptcha_switch_audio').src = IMGROOT + "/audio." + img_format;
      $('recaptcha_switch_img').src = IMGROOT + "/text." + img_format;
      $('recaptcha_whatsthis').src = IMGROOT + "/help." + img_format;
      if (Recaptcha.theme == 'clean') {
        $('recaptcha_logo').src = IMGROOT + "/logo." + img_format;
        $('recaptcha_tagline').src = IMGROOT + "/tagline." + img_format;
      }*/

      Recaptcha.widget.style.display = '';

      if ($OPT.callback) {
        $OPT.callback();
      }
    },

    switch_type : function (new_type) {
	var $C = Recaptcha;
	$C.type = new_type;
	$C.reload ($C.type == 'audio' ? 'a' : 'v');
    },
    
    reload: function (reason) {
	var $C = Recaptcha;
	var $ = $C.$;
	var $ST = RecaptchaState;
	
	$('recaptcha_area').style.cursor = 'progress';
	$('recaptcha_reload_btn').style.cursor = 'progress';
	// disable the button
	//$('recaptcha_reload_btn').onclick = function () { return false; };


	var scriptURL = $ST.server + "reload?c=" + $ST.challenge + "&k=" + $ST.site + "&reason=" + reason + "&type=" + $C.type;
        $C.add_script(scriptURL);
	$C.doing_timeout = reason == 't';    
    },

    finish_reload: function (new_challenge, type) 
    {
	var $C = Recaptcha;
	var $ST = RecaptchaState;
	var $ = $C.$;
	$ST.challenge = new_challenge;
	
	// this should really be the case already...
	$C.type = type;

	$ ('recaptcha_challenge_field').value = $ST.challenge;

	function unwait () {
	    $('recaptcha_area').style.cursor = '';
	    $('recaptcha_reload_btn').style.cursor = '';
	    //$('recaptcha_reload_btn').onclick = null;
	}

	if (type == 'audio') {
	    $('recaptcha_image').style.display = 'none'
	    unwait ();
	    
	    var wavURL = $ST.server + "image?c=" + $ST.challenge;
	    
	    /*if ($C._is_ie()) {
		embedCode = '<object height="40" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" src="' + httpwavurl + '" ><param name="URL" value="' + httpwavurl + '"><param name="autoStart" value="true"><param name="uimode" value="mini"></object>';
	    } else {
		embedCode = '<EMBED SRC="' + wavurl + '" height="40" bgcolor="white" AUTOSTART="true"/>';
	    }*/
	    
	    var embedCode = '<EMBED SRC="' + wavURL + '" height="40" bgcolor="white" AUTOSTART="true"/>';

	    //must update with new challenge
	    $('canthear').href = 'http://api.recaptcha.net/image?c=' + $ST.challenge;
	    
	    $("recaptcha_play_audio").innerHTML = embedCode;
	    $("recaptcha_play_audio").style.display = 'block';

	    $("recaptcha_switch_audio_btn").style.display = 'none';
	    $("recaptcha_switch_img_btn").style.display = '';
	    
	    $("audio_helptext").style.display = '';
	    $("img_helptext").style.display = 'none';
	    
	    $("audio_instructions").style.display = '';
	    $("img_instructions").style.display = 'none';
	    
	    $("recaptcha_response_field_2").style.display = 'none';
	    
	} else if (type == 'image') {
	    $('recaptcha_image').onload = function () {
                
		$('recaptcha_image').style.display = '';
        $("recaptcha_play_audio").style.display = 'none';
		unwait ();
	    }
		
	    $("recaptcha_play_audio").innerHTML = "";

	    $('recaptcha_image').src = $ST.server + 'image?c=' + $ST.challenge;
	    
	    $("recaptcha_switch_img_btn").style.display = 'none';
	    $("recaptcha_switch_audio_btn").style.display = '';
	    
	    $("audio_helptext").style.display = 'none';
	    $("img_helptext").style.display = '';
	    
	    $("audio_instructions").style.display = 'none';
	    $("img_instructions").style.display = '';
	    
	    $("recaptcha_response_field_2").style.display = '';
	}
	
	$C.set_instructions();

	$C.clear_input ();
	/*
	if (!$C.doing_timeout) {
	    $ ('recaptcha_response_field_1').focus ();
	}
	*/

	$C.reset_timer ();
	$C.doing_timeout = false;
    },
    reset_timer : function () {
        var $ST = RecaptchaState;
	clearInterval(Recaptcha.timer_id);
	Recaptcha.timer_id = setInterval ("Recaptcha.reload('t');", ($ST.timeout - 60*5) * 1000);
    },
    showhelp : function () {
	window.open(Recaptcha.helplink,"recaptcha_popup","width=460,height=570,location=no,menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes");
    },
    clear_input : function ()
    {
	var resp1=Recaptcha.$('recaptcha_response_field_1');
	resp1.value = "";
	var resp2=Recaptcha.$('recaptcha_response_field_2');
	resp2.value = "";

    },
    set_instructions : function () {
        if (!Recaptcha.$("recaptcha_instructions")) {
          return;
        }
	var div = Recaptcha.$("recaptcha_instructions")
	if (Recaptcha.type == "image")
	    div.innerHTML = RecaptchaStr.instructions_visual
	else if (Recaptcha.type == "audio")
	    div.innerHTML = RecaptchaStr.instructions_audio
    },
    reloaderror : function (msg) {
        var $=Recaptcha.$;
	$('recaptcha_area').style.cursor = '';
	$('recaptcha_reload_btn').style.cursor = '';
	//$('recaptcha_reload_btn').onclick = null;
	
	$('recaptcha_image').style.display = 'none'
	$("recaptcha_play_audio").innerHTML = msg;
    },
    is_gecko17_or_less : function () {
	var s = navigator.userAgent.toLowerCase() ;
	if (!/gecko\//.test(s))
	    return false;

	var geckoVersion = s.match( /gecko\/(\d+)/ )[1] ; 
	
	// Actually "10" refers to Gecko versions before Firefox 1.5, when 
	// Gecko 1.8 (build 20051111) has been released. 
	
	// Some browser (like Mozilla 1.7.13) may have a Gecko build greater 
	// than 20051111, so we must also check for the revision number not to 
	// be 1.7 (we are assuming that rv < 1.7 will not have build > 20051111). 
	
	// TODO: Future versions may consider the rv number only, but it is 
	// still to check that all Gecko based browser present the rv number. 
	return ( ( geckoVersion < 20051111 ) || ( /rv:1\.7/.test(s) ) ) ; 
    }

};

