var curStep = 1;
var linkCount = 0;
var links = $H({});
var hrefMatch = [];
var hrefMatch2 = [];
var hrefVars = [];

window.onload = init;

function init() {
    
    var date = new Date();
    var cookiestr = 'TEST' + date.getTime();
    document.cookie = "cookietest=" + cookiestr + "; path=/";
    if (document.cookie.indexOf(cookiestr, 0) < 0) {
        Element.show('noCookies');
    }
    else {
        startOver(true);
    }
}
    
function goBack() {
    switch (curStep) {
        case 3:
            step2();
            break;
        case 4:
            if ($F('ignoreHref')) {
                step2();
            }
            else {
                step3();
            }
            break;
        case 5:
            step4();
            break;
        default:
            startOver(false);
    }
}

function startOver(newURL) {

    curStep = 1;

    if (newURL) {
        $('url').value = 'http://';
        $('cookie').value = '';
        Element.hide('cookieField');
    }
    $('ignoreExists').value = '';
    $('title').value = '';
    $('description').value = '';
    $('clickFrame').src = 'about:blank';
    
    Element.hide('ignoreBox');
    ['Class', 'Tree', 'Href'].each( function(c) {
        Element.hide('ignore' + c + 'Box');
        $('ignore' + c).checked = false;
    });
    
    links = $H({});
    $A($('linkList').childNodes).each( function(li) {
        Element.remove(li);
    });
    hrefMatch = hrefMatch2 = hrefVars = [];
    
    Element.hide('goBack');
    ['step2','step3','step4','step5'].each( function(step) { Element.hide(step); });
    Element.show('step1');
    
}

function showCookieField() {
    if ($('cookieField').style.display == 'none') {
        Element.show('cookieField');
    }
    else {
        Element.hide('cookieField');
    }
}

function step2() {
    
    Element.hide('urlError');
    Element.hide('existsError');
    
    // Make sure the URL field isn't empty
    if ( ! /\w/.test($F('url')) || $F('url') == 'http://' ) {
        Effect.Pulsate('url', { duration: 0.5 });
        return false;
    }
    
    // If a cookie is set, make sure the syntax is valid
    if ( $F('cookie') != '' && ! /\=/.test($F('cookie')) ) {
        Element.update('urlError', 'The cookie syntax does not appear to be valid.  Please read <a href="faq-create.html#cookie" target="_blank"> for more information on sending cookies.');
        Element.show('urlError');
        return false;
    }
    
    startIndicator('step1');
    
    new Ajax.Request(
        'new.php',
        {
            parameters: 'action=checkURL&' + Form.serialize('urlForm') + noCacheParam(),
            onSuccess: getPage,
            onFailure: ajaxFailure
        }
    );
    
    return false;
}

function ignoreExists() {
    $('ignoreExists').value = '1';
    step2();
}

function getPage(request) {

    stopIndicator('step1');
    
    var res = JSON.parse(request.responseText);
    if (!res) return ajaxFailure(request);
    res = $H(res);
    
    if (res.error) {
        Element.hide('existsError');
        Element.update('urlError', res.error);
        Element.show('urlError');
    }
    else if (res.exists.length) {        
        Element.hide('urlError');
        
        $A($('existsList').childNodes).each( function(li) {
            Element.remove(li);
        });
        res.exists.each( function(feed) {
            var li = document.createElement('li');
            Element.update(li, '<a href="' + feed + '">' + feed + '</a>');
            $('existsList').appendChild(li);
        });
        
        Element.show('existsError');
    }
    else {
        
        Element.hide('urlError');
        Element.hide('existsError');
        
        if (res.redirect) {
            $('url').value = res.redirect;
        }
        
        $('clickFrame').src = 'new.php?action=getPage&url=' + escape($F('url')) + '&cookie=' + escape($F('cookie'));

        curStep = 2;
        window.scrollTo(0, 0);
    
        // Go to step 2
        ['step1','step3','step4','step5'].each( function(step) { Element.hide(step); });
        if (links.keys().length < 2) {
            Element.hide('checkLinksButton');
        }
        Element.hide('step2Error');
        Element.show('step2');
        Element.show('goBack');
    }
}

function addLink(link) {

    var duplicate = false;
    links.keys().each( function(key) {
        if (links[key].href == link.href) {
            Effect.Pulsate(key, { duration: 0.5 });
            duplicate = true;
        }
    });
    
    if (!duplicate) {    
        linkCount++;        
        var li = document.createElement('li');
        li.id = 'link' + linkCount;
        Element.update(li, '<a href="javascript:removeLink(\'' + li.id + '\')"><img src="images/cross.gif" alt="X" title="Remove Link" class="removeLink" /></a> ' + link.title + ' - ' + link.href);
        li.style.display = 'none';
        $('linkList').appendChild(li);
        links[li.id] = link;
        Effect.Appear(li, { duration: 0.5 });
        
        if (links.keys().length > 1) {
            Element.show('checkLinksButton');
        }
    }
}

function removeLink(id) {

    // Is there a better way to delete a key from a hash?
    var links2 = $H({});
    links.keys().each( function(key) {
        if (key != id) {
            links2[key] = links[key];
        }
    });
    links = links2;
    
    Effect.Fade(id, { duration: 0.5, afterFinish: function() {
        Element.remove(id);
    }});
    
    if (links.keys().length < 2) {
        Element.hide('checkLinksButton');
    }
}

function checkLinks() {

    // Remove any error + highlights
    Element.hide('step2Error');
    links.keys().each( function(id) {
       $(id).style.backgroundColor = '#fff';
    });
    
    startIndicator('checkLinks');
    
    new Ajax.Request(
        'new.php',
        {
            parameters: 'action=checkLinks&links=' + escape(JSON.stringify(links)) + '&url=' + escape($F('url')) + '&cookie=' + escape($F('cookie')) + '&' + Form.serialize('checkLinksForm') + noCacheParam(),
            onSuccess: checkLinksRes,
            onFailure: ajaxFailure
        }
    );
}

function checkLinksRes(request) {
    
    stopIndicator('checkLinks');
    
    var res = JSON.parse(request.responseText);
    if (!res) return ajaxFailure(request);
    res = $H(res);
    
    if (res.error == '') {
        if ($F('ignoreHref')) {
            step4();
        }
        else {
            hrefMatch = res.hrefMatch;
            hrefMatch2 = hrefMatch.entries();
            hrefVars = res.hrefVars;
            step3();
        }
    }
    else {
    
        if (res.links && res.links.length) {
            res.links.each( function(id) {
               $(id).style.backgroundColor = '#fee';
            });
        }
        
        switch (res.error) {
            case 'className':
                Element.update('step2Error', '<strong>Warning:</strong> The highlighted links aren\'t styled the same way as the others.  If you want, I can <a href="javascript:checkLinksIgnore(\'Class\')">ignore link styles</a>, or you can edit the list of links and try again.');
                break;
                
            case 'tree':
                Element.update('step2Error', '<strong>Warning:</strong> The highlighted links aren\'t placed in the same part of the page as the others.  If you want, I can <a href="javascript:checkLinksIgnore(\'Tree\')">ignore page placement</a>, or you can edit the list of links and try again.');
                break;
                
            case 'href':
                Element.update('step2Error', '<strong>Error:</strong> The link destinations don\'t look similar enough.  If you want, I can <a href="javascript:checkLinksIgnore(\'Href\')">ignore link destinations</a>, or you can edit the list of links and try again.');
                break;
                
            default:
                Element.update('step2Error', '<strong>Error:</strong> ' 
                    + res.error);
        }
        
        Element.show('step2Error');
    }
}

function checkLinksIgnore(field) {
    $('ignore' + field).checked = true;
    Element.show('ignore' + field + 'Box');
    Element.show('ignoreBox');
    if (links.keys().length > 1) {
        checkLinks();
    }
}

function step3() {

    curStep = 3;
    window.scrollTo(0, 0);
    
    ['step1','step2','step4','step5'].each( function(step) { Element.hide(step); });
    if (hrefMatch.join() == hrefMatch2.join()) {
        Element.hide('hrefReset');
    }
    
    var i = 0;
    var href_html = '';
    hrefMatch2.each( function(c) {
        if (c == ' ') {
            href_html += '<span id="hrefChar' + i + '" class="wildcard">*</span>';
        }
        else {
            href_html += '<span id="hrefChar' + i + '"><a href="javascript:setWildCard(' + i + ')">' + c + '</a></span>';
        }
        i++;
    });
    
    Element.update('hrefEdit', href_html);
    
    var var_html = '';
    if (hrefVars.length) {
        var_html = '[ Click to wild card variables: ';
        hrefVars.each( function(c) {
            var_html += '<a href="javascript:setVarWildCard(\'' + c + '\')">' + c + '</a> ';
        });
        var_html += ' ]';
    }
    Element.update('varWildCard', var_html);
    
    Element.show('step3');
}

function resetHref() {
    hrefMatch2 = hrefMatch.entries();
    step3();
}

function setWildCard(i) {

    Element.update('hrefChar' + i, '*');
    Element.addClassName('hrefChar' + i, 'wildcard');
    hrefMatch2[i] = ' ';
    Element.show('hrefReset');
}

function setVarWildCard(varname) {
    
    var href = hrefMatch.join('');
    var i = href.indexOf(varname + '=');
    var j = i + varname.length + 1;
    while (j < href.length && hrefMatch[j] != '&') {
        if (hrefMatch2[j] != ' ') {
            setWildCard(j);
        }
        j++;
    }
}

function step4() {
    startIndicator('step4');
    new Ajax.Request(
        'new.php',
        {
            parameters: 'action=getPreview&links=' + escape(JSON.stringify(links)) + '&url=' + escape($F('url')) + '&cookie=' + escape($F('cookie')) + '&' + Form.serialize('checkLinksForm') + '&hrefMatch=' + escape(hrefMatch2.join('')) + noCacheParam(),
            onSuccess: showPreview,
            onFailure: ajaxFailure
        }
    );
}

function showPreview(request) {

    stopIndicator('step4');
    
    curStep = 4;
    window.scrollTo(0, 0);
    
    ['step1','step2','step3','step5'].each( function(step) { Element.hide(step); });
    Element.hide('step4Error');
    Element.hide('step4Done');
    $A($('previewList').childNodes).each( function(li) {
        Element.remove(li);
    });

    var res = JSON.parse(request.responseText);
    if (!res) return ajaxFailure(request);
    res = $H(res);
    
    if (res.links.length) {
        res.links.each( function(link) {
            var li = document.createElement('li');
            Element.update(li, link.title + ' - <a href="' + link.href + '" target="_blank">' + link.href + '</a>');
            $('previewList').appendChild(li);
        });
        $('title').value = res.title;
        $('description').value = res.description;
        Element.show('step4Done');
    }
    else {
        Element.show('step4Error');
    }
    
    Element.show('step4');
}

function step5() {
    
    if ($F('title') == '') {
        Effect.Pulsate('title', { duration: 0.5 });
        alert('You must supply a title for your feed.');
        return false;
    }
    
    if ($F('description') == '') {
        Effect.Pulsate('description', { duration: 0.5 });
        alert('You must supply a description for your feed.');
        return false;
    }
    
    startIndicator('step5');
    new Ajax.Request(
        'new.php',
        {
            parameters: 'action=saveFeed&links=' + escape(JSON.stringify(links)) + '&url=' + escape($F('url')) + '&cookie=' + escape($F('cookie')) + '&' + Form.serialize('checkLinksForm') + '&' + Form.serialize('previewForm') + '&hrefMatch=' + escape(hrefMatch2.join('')) + noCacheParam(),
            onSuccess: step5Finish,
            onFailure: ajaxFailure
        }
    );
}

function step5Finish(request) {
    stopIndicator('step5');
    curStep = 5;
    window.scrollTo(0, 0);
    ['step1','step2','step3','step4'].each( function(step) { Element.hide(step); });
    Element.hide('goBack');
    
    var res = JSON.parse(request.responseText);
    if (!res) return ajaxFailure(request);
    res = $H(res);
    
    if (res.account) {
        Element.update('feedEditURL', '<a href="account.php?class=feed&action=printEdit&id=' + res.feedID + '">click here</a> to edit your feed properties, or');
        Element.show('step5AccountTrue');
    }
    else {
        Element.show('step5AccountFalse');
    }
    
    Element.update('feedURL', '<a href="' + res.feedURL + '"><img src="images/feed.png" alt="Feed" /></a> ' + res.feedURL);
    
    Element.show('step5');
}

function noCacheParam() {
    var now = new Date();
    return '&r=' + now.getTime();
}

function ajaxFailure(request) {
    alert('There was an error processing the request: ' + request.responseText);
}

function startIndicator(step) {
    Element.show(step + 'Indicator');
    $(step + 'Button').disabled = true;
}

function stopIndicator(step) {
    Element.hide(step + 'Indicator');
    $(step + 'Button').disabled = false;
}