﻿function Captcha(imageID, optionsDivID, readCaptchaCodeAnchorText, fetchNewCaptchaCodeAnchorText)
{
    this.image = S.Get(imageID);
    this.defaultImageSrc = this.image.src;
    this.optionsDiv = S.Get(optionsDivID);
    
    this.guid = null;
    this.settingsID = null;
    this.readCaptchaCodeAnchorText = readCaptchaCodeAnchorText;
    this.fetchNewCaptchaCodeAnchorText = fetchNewCaptchaCodeAnchorText;
    this.readUrl = null;
    
    this.buildOptionDivHtml();
}

Captcha.prototype.buildOptionDivHtml = function()
{
    var readAnchorText = document.createTextNode(this.readCaptchaCodeAnchorText);
    var readAnchor = document.createElement("a");
    readAnchor.href = "javascript: void(null);";
    readAnchor.appendChild(readAnchorText);
    this.optionsDiv.appendChild(readAnchor);
    
    S.Event.add(readAnchor, "click", this.read.bind(this));
    
    var spacerText = document.createTextNode(" - ");  
    this.optionsDiv.appendChild(spacerText);
    
    var refreshAnchorText = document.createTextNode(this.fetchNewCaptchaCodeAnchorText);
    var refreshAnchor = document.createElement("a");
    refreshAnchor.href = "javascript: void(null);";
    refreshAnchor.appendChild(refreshAnchorText);
    this.optionsDiv.appendChild(refreshAnchor);
    
    S.Event.add(refreshAnchor, "click", this.refresh.bind(this));
}

Captcha.prototype.read = function()
{
    var popup = window.open(this.readUrl, "CaptchaReader", "height=336,width=770,dialog=yes,modal=yes,status=yes,toolbar=no,menubar=no,location=no");
    popup.focus();
}

Captcha.prototype.refresh = function()
{
    this.image.src = "{0}&Date={1}&SettingsID={2}&Refresh=true".format(this.defaultImageSrc, (new Date()).valueOf(), this.settingsID);
}