function setIframeDimensions(){
    var frame = $('frame');
    var theSideReel = $('theSideReel');
    var frameWidth = document.viewport.getWidth() - theSideReel.getWidth();
    frame.style.width = frameWidth + 'px';
    frame.style.height = document.viewport.getHeight() + 'px';
    frame.style.left = theSideReel.getWidth() + 'px';
    //IE6 footer positioning fix
    $('main').style.height = document.viewport.getHeight() + 'px';
}

function toggleSideBar(){
    $('main').toggle();
    $('toggleLink').toggleClassName('on');
    setIframeDimensions();
}


//Editing Actions
function showEdit(){
    $('details').style.display = 'none';
    $('addWatchForm').style.display = 'block';
}

function hideAddWatchLinkBox(){
    $('details').style.display = 'block';
    $('addWatchForm').style.display = 'none';
}

function addWatchLink() {
    resetAddWatchLinkBox();
    $('addWatchLinkSubmit').value = "Add";
    $('addWatchLinkId').value = "";
    $("addWatchLinkUrl").focus();
}

function eWL(linkId, linkUrl, linkSeason, linkEpisode, linkTitle) {
    showEdit()
    addWatchLink();
    populateAddWatchLinkBox(linkUrl, linkSeason, linkEpisode, linkTitle, linkId);
    $('addWatchLinkSubmit').value = "Update";
    $('addWatchLinkUrl').disable();
    $("addWatchLinkSeasonNumber").focus();
    //always return false.  This is a "clever hack" to keep the page from refreshing when links that call this function are clicked
    return false;
}

function populateAddWatchLinkBox(url, season, episode, title, id) {
    $('addWatchLinkUrl').value = url;
    $('addWatchLinkSeasonNumber').value = season;
    $('addWatchLinkEpisodeNumber').value = episode;
    $('addWatchLinkTitle').value = title;
    if (id) {
        $('addWatchLinkId').value = id;
    }
}

function resetAddWatchLinkBox() {
    Form.getInputs('addWatchLinkForm', 'text').each(function(input) {
        input.clear();
        input.enable();
    });
    $('addWatchLinkSubmit').enable();
    updateEditBoxMessages("");
    //TODO: uncomment when we want parts back
    //    $('addWatchLinkPartsGroup').innerHTML = "";
}

//Remove Functions
function rateWatchLink(watchLinkId, atomIdAsLink, rating) {
    var url = atomIdAsLink + "/_watchlink/" + watchLinkId + "/_rating";
    return new makeAjaxPost(url, {action:"add", rating: rating},
            handleRateWatchLinkReturn, handleRateWatchLinkReturn)
}

function handleRateWatchLinkReturn() {
    document.getElementById("watchLinkRating").innerHTML = "Thanks for the feedback!";
}

//Admin Functions
function watchLinkManagerRemove(atomIdAsLink, watchLinkId) {
    return makeAjaxPost(atomIdAsLink + "/_watchlink/" + watchLinkId, {action: 'delete'},
            watchLinkManagerRemoveSuccess, watchLinkManagerRemoveFailure)
}

function watchLinkManagerRemoveSuccess() {
    updateWatchLinkTools("removed");
}

function watchLinkManagerRemoveFailure() {
    updateWatchLinkTools("error removing watchlink");
}

function watchLinkManagerAdd(atomIdAsLink, url, season, episode, title) {
    return makeAjaxPost(atomIdAsLink + "/_watchlink", {action: 'add', url: url, season: season, episode: episode, title: title},
            watchLinkManagerAddSuccess, watchLinkManagerAddFailure)
}

function watchLinkManagerAddSuccess() {
    updateWatchLinkTools("added");
}

function watchLinkManagerAddFailure() {
    updateWatchLinkTools("error adding watchlink");
}

function updateWatchLinkTools(message) {
    $('watchLinkTools').update(message);
}

//Validate
/*
 * Validate the url for each part in the add watch link interface
 * add an error message for each incorrect url
*/
function validate() {
    $('addWatchLinkMessages').update();

    var nonEmptyInputs = $($('addWatchLinkForm').getElementsByClassName("addWatchLinkPart")).findAll(function(input) {
        return !input.getValue().empty();
    });

    var error = checkUrlInputsForError(nonEmptyInputs);
    if (error) {
        $('addWatchLinkMessages').appendChild(error);
        return false;
    }
    return true;
}

function checkUrlInputsForError(inputs) {
    var error;
    if (inputs.size() > 0) {
        var invalidUrls = validateUrls(inputs.pluck('value'));
        // if any of the URLs failed the validity check
        if (invalidUrls.size() > 0) {
            error = generateErrorList(invalidUrls);
        }
    } else {
        error = makeDocumentElement("span", "You must enter a URL", new Hash({'class':'addWatchLinkErrorMessage'}));
    }
    return error;
}

function generateErrorList(invalidUrls) {
    var errorList = makeDocumentElement("ul");
    invalidUrls.each(function(url) {
        errorList.appendChild(makeDocumentElement("li", "Invalid URL: " + url.escapeHTML(), new Hash({'class':'addWatchLinkErrorMessage'})));
    });
    return errorList;
}

function validateUrls(values) {
    return values.findAll(function(url) {
        return !isValidUrl(url);
    });
}

//Ad WatchLinks
function addWatchLinkRequest(values) {
    if (values['addWatchLinkId']) { // edit
        makeAjaxPost(atomLink + "/_watchlink/" + values['addWatchLinkId'], { action: 'edit',
            season: values['addWatchLinkSeasonNumber'], episode: values['addWatchLinkEpisodeNumber'], title: values['addWatchLinkTitle']},
                handleUpdateWatchLinkSuccess, handleUpdateWatchLinkFailure, handleFailed403WatchlinkResponse);
        updateEditBoxMessages("updating link ...");
    } else { //add
        makeAjaxGet(atomLink + "/_watchlinkvalidator", {url: values['addWatchLinkUrl']},
                handleValidateWatchLinkSuccess, handleValidateWatchLinkFailure);
    }
    $('addWatchLinkSubmit').disable();
}

function makeAjaxPost(url, postParams, successFunc, errorFunc) {
    return makeAjaxRequest(url, "POST", postParams, successFunc, errorFunc);
}

/* this is the callback function for a successful AJAX request
 *
 * transport (XmlHttpRequest) - this contains the data returned from server
*/
function handleUpdateWatchLinkSuccess(transport) {
    var linkDetailsContent = transport.responseText;
    $('linkDetailsInner').update(linkDetailsContent);
}

function handleLoadWatchLinksSuccess(transport) {
    var watchListContents = transport.responseText;
    if (watchListContents) {
        hideAddWatchLinkBox();
        updateWatchList(watchListContents);
    } else {
        updateEditBoxMessages(DEFAULT_ERROR_TEXT);
    }
}

function updateEditBoxMessages(message) {
    $('addWatchLinkMessages').style.display = 'block';
    $('addWatchLinkMessages').update(message);
}

function handleValidateWatchLinkSuccess(transport) {
    var response = transport.responseText.evalJSON().response;
    if (response.value == "OK" || response.value == "UNKNOWN") {
        var values = $('addWatchLinkForm').serialize(true);
        makeAjaxPost(atomLink + "/_watchlink", {action: 'add', url: values['addWatchLinkUrl'],
            season: values['addWatchLinkSeasonNumber'], episode: values['addWatchLinkEpisodeNumber'], title: values['addWatchLinkTitle']},
                handleUpdateWatchLinkSuccess, handleUpdateWatchLinkFailure, handleFailed403WatchlinkResponse);
        updateEditBoxMessages("updating links...");
    } else if (response.value == "DUPLICATE") {
        updateEditBoxForFailedValidation("A link to this URL already exists");
    } else if (response.value == "INVALID") {
        updateEditBoxForFailedValidation("This link does not appear to be valid.");
    } else {
        // a "success" response with an unexpected value. This should never happen.
        handleValidateWatchLinkFailure(transport);
    }
}

function updateEditBoxForFailedValidation(message) {
    updateEditBoxMessages(message);
    $("addWatchLinkUrl").focus();
    $("addWatchLinkSubmit").enable();
}

function handleValidateWatchLinkFailure() {

    updateEditBoxMessages(DEFAULT_ERROR_TEXT);
}

function updateWatchList(watchListContents) {
    $('watchList').innerHTML = watchListContents;
    initialize();
}

function canonicalizeId(id) {
    return (id.toString()).gsub(/_/, '');
}

function handleUpdateWatchLinkFailure() {
    updateEditBoxMessages(DEFAULT_ERROR_TEXT);
}

function handleLoadWatchLinksFailure() {
    updateEditBoxMessages(DEFAULT_ERROR_TEXT);
}

/* this is the callback function for a failed AJAX request
 *
 * transport (XmlHttpRequest) - this contains the data returned from server
*/
function handleRemoveWatchLinkFailure() {
    updateConfirmationBoxForError(DEFAULT_ERROR_TEXT);
}

function handleFailed403WatchlinkResponse() {
    window.location.reload();
}

/* update the confirmation UI to show an error message
 *
 * errorText (String) - something about our action team getting busy
*/
function updateConfirmationBoxForError(errorText) {
    $("killWatchLink").remove();
    $("pardonWatchLink").remove();
    $("removeWatchLinkConfirmationText").innerHTML = errorText;
    $("removeWatchLinkConfirmationText").addClassName("error");
    window.setTimeout(hideConfirmationBox, 2000);
}

function makeAjaxRequest(url, method, params, successFunc, errorFunc) {
    var request = new Ajax.Request(url,
    {
        method: method,
        parameters: params,
        requestHeaders: {Accept: "application/json"},
        onSuccess: successFunc,
        onFailure: errorFunc
    });
    return request;
}

function isValidUrl(url) {
    var regExp = /^\s*((http(s)?|ftp):\/\/)?([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,6}(\/[\S]*)?\s*$/i;
    return regExp.test(url);
}

function editWatchLinkRequestFromViewer(values){
    makeAjaxPost(atomLink + "/_watchlink/" + values['addWatchLinkId'], { action: 'edit',
        season: values['addWatchLinkSeasonNumber'], episode: values['addWatchLinkEpisodeNumber'], title: values['addWatchLinkTitle']},
            handleUpdateWatchLinkSuccess, handleUpdateWatchLinkFailure, handleFailed403WatchlinkResponse);
}

/*Add to Favorites
--------------------------------------------------*/
function submitFavoritesRequest(action, atomId, watchLinkId) {
    var favesCallback;
    if (action == "add") {
        makeAjaxPost('/_user/_favorites', { action: action,
            atomId: atomId, watchLinkId: watchLinkId},
                handleAddFavoriteResponse, handleAddFavoriteResponse)
    } else {
        makeAjaxPost('/_user/_favorites', { action: action,
            atomId: atomId, watchLinkId: watchLinkId},
                handleRemoveFavoriteResponse(atomId, watchLinkId), handleRemoveFavoriteResponse(atomId, watchLinkId))
    }
}

function handleAddFavoriteResponse() {
    $('addToFavoritesBox').update('<span>Added to Favorites</span>');
}

function handleRemoveFavoriteResponse(atomId, watchLinkId) {
    var favoriteBoxId = 'favoriteItem' + atomId;
    if (watchLinkId != null) {
        favoriteBoxId = 'favoriteItem' + atomId + "_" + watchLinkId;
    }
    $(favoriteBoxId).hide();
}




