﻿
// Constants

var URL_STARTER = "http://";
var URL_PREFIX_REGEX = /^(http:\/\/|https:\/\/)/i;

// Elements

var mainForm;
var urlInput;
var errorTextPara;

// Core functions

function init() {
    initElements();
    initPart1();
}

function initElements() {
    mainForm = $("create-form");
    urlInput = $("url-textbox").getElementsByTagName("input")[0];
    errorTextPara = $("error-text");
}


// Part 1 functions

function initPart1() {
    Seadragon.Utils.addEvent(mainForm, "submit", onMainFormSubmit);

    // if the textbox has our default starter text in it, remove it when the
    // field gets focus, and re-add it on blur if the textbox is empty. if the
    // textbox has other text in it, select it on focus. note for all of these
    // that it's only on "focus", not on "click". the user should be able to
    // place the caret then (bug 4064).
    Seadragon.Utils.addEvent(urlInput, "focus", onUrlInputFocus);
    Seadragon.Utils.addEvent(urlInput, "blur", onUrlInputBlur);
    
    // if an error message was populated on the server, show it
    if (SERVER.Error) {
        setErrorText(SERVER.Error);
    }
}

function onMainFormSubmit(event) {
    if (!validateUrlInput()) {
        Seadragon.Utils.cancelEvent(event); // don't let the form change the page
        return;
    }
}

function onUrlInputFocus(event) {
    if (urlInput.value == URL_STARTER) {
        urlInput.value = "";
    } else {
        urlInput.select();
    }
}

function onUrlInputBlur(event) {
    if (!urlInput.value) {
        urlInput.value = URL_STARTER;
    }
}

function validateUrlInput() {
    var url = urlInput.value || "";
    var urlPost = url.replace(URL_PREFIX_REGEX, "");

    // using urlPost to treat "" the same as just "http[s]://"
    if (!urlPost) {
        setErrorText("Paste an image URL into the textbox, then click Create.");
        return false;
    }

    if (!URL_PREFIX_REGEX.test(url)) {
        setErrorText("Please provide the full URL, including the \"http://\" or \"https://\".");
        return false;
    }

    clearErrorText();

    // MIME type checking on server
    // replaces client-side detection
    return true;
}

function setErrorText(text) {
    errorTextPara.innerHTML = text || "";
    if (text) {
        errorTextPara.style.display = "";   // show
    } else {
        errorTextPara.style.display = "none";   // hide
    }
}

function clearErrorText() {
    setErrorText("");
}

// Immediate execution

init();
