/* some dopey simple javascript for fiveworst.com */

// global fucking variables, lazy-time, i like....
var submit_tries = 0;
var DEBUG = false;

// any fancy page init crap...
function init() {
    
    // fucking MSIE!!! oh well at least it's just the menu and search.
    try {
		if (navigator.userAgent.match(/MSIE/)) {
		    var busted = [
		        'Menu',
		        'MenuBest',
		        'MenuRecent',
		        'MenuAll',
		        'MenuAdd',
		        'MenuSearch'
		    ];
		    for (var i=0; i < busted.length; i++) {
		        $(busted[i]).id += '_MSIE';
		    }
			$('MenuSearch_MSIE').onclick = function() { void(0); };
		}
	}
	catch(e) {
		// ouch.
		// console.log(e);
	}
	
	
    // branch on id if available.
    var id = '';
    if (document.body && document.body.id) {
        id = document.body.id;
    }
    
    // entry page tweaks.
    if (id == 'Add') {
        prepop_entry_form();
    }
    
    // make sure errors are dismissable.
    if ($('Error') && !$('ErrorDismiss')) {
        add_error_dismiss();
    }
    
    // spotlight goes off on random clicks
    document.body.onclick = function() {toggle_spotlight(true);};
    
}

// redirect spotlight to google search until/unless we integrate co-op.
function goo() {
    
    var loc = location.href;
    if (loc && loc.match(/spot.html/) && loc.match(/q\=/)) {
        loc = loc.replace(/fiveworst.com\/search\/spot.html/,'google.com/search');
        loc += '%20site%3Awww.fiveworst.com';
        // also tweak for testing:
        loc = loc.replace(/\/local\./,'/www.');
        location.replace(loc);
    }
    else {
        // wtf, bad entry point.
        // console.log(loc);
       location.replace('/search/');
    }
    
}

// spotlight-style search doodad, just for funsky.
var _ignore_bodyClick = false;
function toggle_spotlight(bodyClick) {
    
    // ignore "off" clicks from body if too close to last real click.
    if (bodyClick && _ignore_bodyClick) {
        _ignore_bodyClick = false;
        return;
    }
    else if (!bodyClick) {
        _ignore_bodyClick = true;
    }
    
    // just toggle visibility if the div exists.
    if ($('Spotlight')) {
        
        // if we are coming from the body, just turn it off.
        if (bodyClick) {
            // console.log($('Spotlight'));
            $('Spotlight').style.display = 'none';
            
        }
        else if ($('Spotlight').style.display != 'none') {
            $('Spotlight').style.display = 'none';
        }
        else {
            $('Spotlight').style.display = 'block';
        }
        return false; // don't follow the link.
    }
    else if (bodyClick) {
        return;
    }

    // just show it if it's hidden.
    
    // create a spotlight-esque div.  (TODO: refactor for mochi-style)
    var div = document.createElement('div');
    div.id = 'Spotlight';
    // we don't go directly to google or we would lose knowledge of the
    // searches.  longer-term this should go via coop and stay on the sam
    // page.
    var form = document.createElement('form');
    form.action = '/search/spot.html';
    var input = document.createElement('input');
    input.type = 'text';
    input.name = 'q';
    form.appendChild(document.createTextNode('Search'));
    form.appendChild(input);
    var submit = document.createElement('input');
    // don't let people search for nothingness.
    form.onsubmit = function() {
       var v = form.q.value;
       if (!v || !v.match(/\S/)) {
           return false;
        }
    }
    div.appendChild(form);
    
    // and we don't want the form going away when the event gets passed through.
    div.onclick = function() { _ignore_bodyClick = true; };
    $('Header').appendChild(div);
    
    // do NOT follow the link.
    return false;
}

// basic validation of entry form (cgi validates too).
function validate_entry(f) {

    // zap any existing error.
    clear_errors();
    
    var errs = [];
    
    // going for siiiiimple for now.
    var required = {
        title   : 'Title',
        worst_1 : 'First Worst',
        worst_2 : 'Second Worst',
        worst_3 : 'Third Worst',
        worst_4 : 'Fourth Worst',
        worst_5 : 'Fifth Worst',
        email   : 'Email Address',
        author  : 'Your Name'
        
    };
    for (var k in required) {
        
        var v = spaceless(f[k].value);
        if (!v || !v.length) {
            errs.push(required[k] + ' is required.');
        }
    }
    
    if (errs.length) {
        
        // add 'em like we would from the CGI, more or less.
        // (but try to make it fresh-ish)
        var openers = [
            "Oops, something is not right...",
            "Hmmm, still not quite right:",
            "Uh-oh, we're still not there yet...",
            "Nope.  Nope.  Nope.",
            "Really, are you sure about that?  Not quite:",
            "Ugh. Either you're a little slow today, or the script is broken.",
            "I dunno about this.  That's, what, your seventh try?",
            "If this gets any worse you might as well give up."
        ];
        if (submit_tries >= openers.length) {
            openers[submit_tries] = 'Oh God, it must be broken...';
        }
        
        add_form_err(f,openers[submit_tries]);
        for (var i=0; i<errs.length;i++) {
            add_form_err(f,errs[i]);
        }
        
        add_error_dismiss();
        
        submit_tries ++;
        return false;
    }
    
    return true;
    
}
// ...right now i like these below the form.
function add_form_err(f,txt) {
    
    var d = $('Error');
    if (!d) {
        d = document.createElement('div');
        d.id = 'Error';
        f.appendChild(d);
    }
    
    var p = document.createElement('p');
    p.appendChild(document.createTextNode(txt));
    d.appendChild(p);
    d.style.display = 'block'; // see clear_errors
    
}

// get rid of the errors.
function clear_errors() {
    
    var d = $('Error');
    if (d) {
        while (d.firstChild) {
            d.removeChild(d.firstChild);
        }
        d.style.display = 'none';
    }
    
}

// add a "dismiss" button to errors since they're Fixed.
// (late night JS anyone?)
function add_error_dismiss() {
    
    if ($('Error')) {
        
        var ok_txts = [
            'OK',
            'Close',
            'Alright Already',
            'Sorry',
            'Oops',
            'Gotcha',
            'Do better next time',
            'Leave me alone',
            'Go away'
        ];
        var txt = ok_txts[parseInt(Math.random()*ok_txts.length)];
        var p = document.createElement('p');
        p.id = 'ErrorDismiss';
        
        var a = document.createElement('a');
        a.href = '#';
        a.onclick = clear_errors;
        a.appendChild(document.createTextNode(txt));
        p.appendChild(a);
        
        $('Error').appendChild(p);
        
    }
}

// do a total strip of spaces
function spaceless(val) {
    
    if (val) {
        val = val.replace(/\s+/,'');
    }
    return val;
    
}

// populate form based on query string.
function prepop_entry_form() {
    
    var f = $('Entry');
    if (!f) {
        console.log('Missing entry form.');
        return;
    }
    
    // whatever's in the QA.
    try {
        var qs = window.location.search.substring(1);
        var pairs = qs.split('&');
        for (var i=0;i<pairs.length;i++) {
            var pair = pairs[i].split("=");
            var k = unescape(pair[0]);
            var v = unescape(pair[1]);
            if (k && f[k]) {
                f[k].value = v;
                console.debug('set ' + k + ' to ' + v);
            }
            else if (k) {
                console.debug('no form element ' + k);
            }
        }
        
    }
    catch(e) {
        console.warn('QS parse failed: ' + e);
    }
    
}



/* generic lightweight stuff: */

function $(id) {
 
   return document.getElementById(id);
    
}


// debugging: always use a real console, otherwise depend on DEBUG global.
if (typeof(console) == 'undefined') {
    
   console = {
       
        write: function(msg) {
            if (!DEBUG) {
                return;
            }
            var p = document.createElement('pre');
            p.className = 'console';
            p.appendChild(document.createTextNode(msg));
            document.body.appendChild(p);
        },
        log: function(msg) {
            console.write(msg);
        },
        warn: function(msg) {
            console.write(msg);
        },
        info: function(msg) {
            console.write(msg);
        },
        error: function(msg) {
            console.write(msg);
        },
        debug: function(msg) {
            console.write(msg);
        }
   };
}


