function validateUsername(value){
    new Ajax.Request('/account/username_avail/' + value, {
        method: "get",
        onComplete: function(request){
            if (request.status != 200) {
                $('uiderror').innerHTML = "";
            }
            else {
                $('uiderror').innerHTML = request.responseText;
                if (request.responseText.match('not available')) {
                    s.sendFormEvent('e', 'registration', 'registration', 'Username: already taken');
                }
                else 
                    if (request.responseText.match('is not valid')) {
                        s.sendFormEvent('e', 'registration', 'registration', 'Username: invalid');
                    }
            }
        }
    });
}

//hideshow any target ID Used only in accounts....
function targetHideShow(contId, newStyle, oldStyle){
    var styleObject = document.getElementById(contId).style;
    
    if (styleObject.display == newStyle) {
        styleObject.display = oldStyle;
    }
    else {
        styleObject.display = newStyle;
    }
}

//Start new Textarea character counter -------------------------------------
// TODO: make sure counter is set correctly initially once we can edit captions
function countChars(textArea, counterField){
    var _textArea = $(textArea);
    var maxLength = parseInt(_textArea.getAttribute('maxlength'), 10);
    
    if (_textArea.value.length > maxLength) {
        alert("Your message may not exceed " + maxLength + " characters in length.");
        _textArea.value = _textArea.value.substring(0, maxLength);
    }
    $(counterField).innerHTML = maxLength - _textArea.value.length;
}

//	<textarea cols="60" id="description" maxlength="300" name="description" onkeyup="countChars(this, 'message-counter');" rows="5"></textarea>
// <span class="textareacounter"><span id="message-counter">300</span> characters remaining</span>



function wordCounter(textArea, counterfield) {
	var _textArea = $(textArea);
    var maxLength = parseInt(_textArea.getAttribute('maxwords'), 10);

	wordcounter=0;
	for (x=0; x<_textArea.value.length; x++) {
      	if ((_textArea.value.charAt(x).match(/\s/)) && (_textArea.value.charAt(x-1).match(/\S/)))
			{wordcounter++}  // Counts the spaces while ignoring double spaces, usually one in between each word.
      	if (wordcounter >= maxLength) {
			alert("Your message may not exceed " + maxLength + " words in length.");
			_textArea.value = _textArea.value.substring(0, x);
		}
        $(counterfield).innerHTML = (" There are " + (maxLength - wordcounter) + " words remaining.");
    }
}


function createCookie(name, value, days){
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/" + this.domain ? "; domain=" + this.domain : "";
}

function readCookie(name){
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) === 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}

function eraseCookie(name, path, domain){
    if (readCookie(name)) {
        document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
}


// BASE64 STUFF
// DON'T DELETE BASE64 STUFF - this is needed by the ad code. thanks! -chris
function urlDecode(str){
    str = str.replace(new RegExp('\\+', 'g'), ' ');
    return unescape(str);
}

function urlEncode(str){
    str = escape(str);
    str = str.replace(new RegExp('\\+', 'g'), '%2B');
    return str.replace(new RegExp('%20', 'g'), '+');
}

var END_OF_INPUT = -1;

var base64Chars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'];

var reverseBase64Chars = [];
for (var i = 0; i < base64Chars.length; i++) {
    reverseBase64Chars[base64Chars[i]] = i;
}

var base64Str;
var base64Count;
function setBase64Str(str){
    base64Str = str;
    base64Count = 0;
}

function readBase64(){
    if (!base64Str) {
		return END_OF_INPUT;
	}
    if (base64Count >= base64Str.length) {
		return END_OF_INPUT;
	}
    var c = base64Str.charCodeAt(base64Count) & 0xff;
    base64Count++;
    return c;
}

function encodeBase64(str){
    setBase64Str(str);
    var result = '';
    var inBuffer = new Array(3);
    var lineCount = 0;
    var done = false;
    while (!done && (inBuffer[0] = readBase64()) != END_OF_INPUT) {
        inBuffer[1] = readBase64();
        inBuffer[2] = readBase64();
        result += (base64Chars[inBuffer[0] >> 2]);
        if (inBuffer[1] != END_OF_INPUT) {
            result += (base64Chars[((inBuffer[0] << 4) & 0x30) | (inBuffer[1] >> 4)]);
            if (inBuffer[2] != END_OF_INPUT) {
                result += (base64Chars[((inBuffer[1] << 2) & 0x3c) | (inBuffer[2] >> 6)]);
                result += (base64Chars[inBuffer[2] & 0x3F]);
            }
            else {
                result += (base64Chars[((inBuffer[1] << 2) & 0x3c)]);
                result += ('=');
                done = true;
            }
        }
        else {
            result += (base64Chars[((inBuffer[0] << 4) & 0x30)]);
            result += ('=');
            result += ('=');
            done = true;
        }
        lineCount += 4;
        if (lineCount >= 76) {
            result += ('\n');
            lineCount = 0;
        }
    }
    return result;
}

function readReverseBase64(){
    if (!base64Str) {
		return END_OF_INPUT;
	}
    while (true) {
        if (base64Count >= base64Str.length) {
			return END_OF_INPUT;
		}
        var nextCharacter = base64Str.charAt(base64Count);
        base64Count++;
        if (reverseBase64Chars[nextCharacter]) {
            return reverseBase64Chars[nextCharacter];
        }
        if (nextCharacter == 'A') {
			return 0;
		}
    }
    return END_OF_INPUT;
}

function ntos(n){
    n = n.toString(16);
    if (n.length == 1) {
		n = "0" + n;
	}
    n = "%" + n;
    return unescape(n);
}

function decodeBase64(str){
    setBase64Str(str);
    var result = "";
    var inBuffer = new Array(4);
    var done = false;
    while (!done && (inBuffer[0] = readReverseBase64()) != END_OF_INPUT &&
    (inBuffer[1] = readReverseBase64()) != END_OF_INPUT) {
        inBuffer[2] = readReverseBase64();
        inBuffer[3] = readReverseBase64();
        result += ntos((((inBuffer[0] << 2) & 0xff) | inBuffer[1] >> 4));
        if (inBuffer[2] != END_OF_INPUT) {
            result += ntos((((inBuffer[1] << 4) & 0xff) | inBuffer[2] >> 2));
            if (inBuffer[3] != END_OF_INPUT) {
                result += ntos((((inBuffer[2] << 6) & 0xff) | inBuffer[3]));
            }
            else {
                done = true;
            }
        }
        else {
            done = true;
        }
    }
    return result;
}

var digitArray = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
function toHex(n){
    var result = '';
    var start = true;
    for (var i = 32; i > 0;) {
        i -= 4;
        var digit = (n >> i) & 0xf;
        if (!start || digit !== 0) {
            start = false;
            result += digitArray[digit];
        }
    }
    return (result === '' ? '0' : result);
}

function pad(str, len, _pad){
    var result = str;
    for (var i = str.length; i < len; i++) {
        result = _pad + result;
    }
    return result;
}

function encodeHex(str){
    var result = "";
    for (var i = 0; i < str.length; i++) {
        result += pad(toHex(str.charCodeAt(i) & 0xff), 2, '0');
    }
    return result;
}

function decodeHex(str){
    str = str.replace(new RegExp("s/[^0-9a-zA-Z]//g"));
    var result = "";
    var nextchar = "";
    for (var i = 0; i < str.length; i++) {
        nextchar += str.charAt(i);
        if (nextchar.length == 2) {
            result += ntos(eval('0x' + nextchar));
            nextchar = "";
        }
    }
    return result;
    
}

// END BASE64 STUFF


// js approximation of Rails' function via Typo
function distance_of_time_in_words(minutes){
    if (minutes.isNaN) {
        return "";
    }
    minutes = Math.abs(minutes);
    if (minutes < 1) {
        return ('less than a minute');
    }
    if (minutes < 2) {
        return ('1 minute');
    }
    if (minutes < 50) {
        return (minutes + ' minutes');
    }
    if (minutes < 90) {
        return ('about 1 hour');
    }
    if (minutes < 1080) {
        return (Math.round(minutes / 60) + ' hours');
    }
    if (minutes < 1440) {
        return ('1 day');
    }
    if (minutes < 2880) {
        return ('about 1 day');
    }
    else {
        return (Math.round(minutes / 1440) + ' days');
    }
}

// used by js_distance_of_time_in_words
function get_local_time_for_date(time){
    var system_date = new Date(time);
    var user_date = new Date();
    var delta_minutes = Math.floor((user_date - system_date) / (60 * 1000));
    if (Math.abs(delta_minutes) <= (52 * 7 * 24 * 60)) { // 1 year
        var distance = distance_of_time_in_words(delta_minutes);
        if (delta_minutes < 0) {
            return distance + ' from now';
        }
        else {
            return distance + ' ago';
        }
    }
    else {
        return 'on ' + system_date.toLocaleDateString();
    }
}

// TERSE VERSION of js approximation of Rails' function via Typo
function distance_of_time_in_words_terse(minutes){
    if (minutes.isNaN) {
        return "";
    }
    minutes = Math.abs(minutes);
    if (minutes < 1) {
        return ('< 1 min.');
    }
    if (minutes < 2) {
        return ('1 minute');
    }
    if (minutes < 50) {
        return (minutes + ' mins.');
    }
    if (minutes < 90) {
        return ('> 1 hour');
    }
    if (minutes < 1080) {
        return (Math.round(minutes / 60) + ' hrs.');
    }
    if (minutes < 1440) {
        return ('1 day');
    }
    if (minutes < 2880) {
        return ('> 1 day');
    }
    else {
        return (Math.round(minutes / 1440) + ' days');
    }
}

// TERSE VERSION used by js_distance_of_time_in_words
function get_local_time_for_date_terse(time){
    var system_date = new Date(time);
    var user_date = new Date();
    var delta_minutes = Math.floor((user_date - system_date) / (60 * 1000));
    if (Math.abs(delta_minutes) <= (52 * 7 * 24 * 60)) { // 1 year
        var distance = distance_of_time_in_words_terse(delta_minutes);
        if (delta_minutes < 0) {
            return distance + ' from now';
        }
        else {
            return distance + ' ago';
        }
    }
    else {
        return 'on ' + system_date.toLocaleDateString();
    }
}

// more time goodness from Typo
function show_dates_as_local_time(){
    var spans = document.getElementsByTagName('span');
    for (var i = 0; i < spans.length; i++) {
        if (spans[i].className.match(/\bcontent_date\b/i)) {
            spans[i].innerHTML = get_local_time_for_date(spans[i].title);
        }
    }
}


/* mail functions */


function checkboxes(value){
    var x = document.messages.getElementsByTagName('input');
    for (var k = 0; k < x.length; ++k) {
        var box = x[k];
        if (box.type.toLowerCase() == "checkbox") {
            var temp = box.onchange;
            box.onchange = null;
            box.checked = value;
            box.onchange = temp;
        }
    }
}

function selectRead(){
    checkboxes(false);
    var ids = document.messages.old_ids.value.split(',');
    for (var k = 0; k < ids.length; ++k) {
        document.getElementById('msg[' + ids[k] + ']').checked = true;
    }
}

function selectNew(){
    checkboxes(false);
    var ids = document.messages.new_ids.value.split(',');
    for (var k = 0; k < ids.length; ++k) {
        document.getElementById('msg[' + ids[k] + ']').checked = true;
    }
}

function generic_flipper(class_to_hide, parent_id, delay) {
	$(parent_id).select('div.' + class_to_hide).invoke('hide');
	$(parent_id).select('div.' + class_to_hide)[0].show();
	setTimeout("switch_frame('" + class_to_hide + "','" + parent_id + "',0, " + delay + ")", delay)
}

function switch_frame(class_to_hide, parent_id, index, delay) {
	var divs = $(parent_id).select('div.' + class_to_hide);
	var next = (index + 1) % divs.length;

	divs[index].fade();
	setTimeout("$('" + parent_id + "').select('div." + class_to_hide + "')[" + next +"].appear();", 450);

	setTimeout("switch_frame('" + class_to_hide + "','" + parent_id + "'," + next + ", " + delay + ")", delay);
}

var lock = false;
var active_notable = 0;

function notable_flipper(class_to_hide, parent_id){

    show_notable_image(active_notable, class_to_hide, parent_id);
    active_notable = (active_notable + 1) % 5;
}


function show_notable_image(index, class_to_hide, parent_id){
    if (lock == true) 
        return;
    lock = true;
    
    current = $("photo_" + index)
    if (!current.visible()) {
    
        $(parent_id).select('li').invoke('removeClassName', "active");
        
        $("photo_li_" + index).addClassName("active");
        
        $(parent_id).select('div.' + class_to_hide).invoke('hide');
        
        current.appear();
    }
    
    lock = false;
}

var lock2 = false;
function show_city_list(id_to_show, class_to_hide, parent_id, active_a){
    if (lock2 == true) 
        return;
    lock2 = true;
    if (!$(id_to_show).visible()) {
        $(parent_id).select('a').invoke('removeClassName', "active");
        active_a.addClassName("active");
        $(parent_id).select('div.' + class_to_hide).invoke('hide');
        //$(id_to_show).appear();
        $(id_to_show).show();
    }
    lock2 = false;
}


function SpecificYearHandler(selectElementId, yearElementId){
    var DODval = $(selectElementId).value;
    
    if (DODval == 'Year') {
        $(yearElementId).show();
    }
    else {
        $(yearElementId).hide();
    }
}

var show_flash_js = false;
function detectFlashOrShowContent(flashDivId, alternateDivId, force_noflash){
	var playerVersion = swfobject.getFlashPlayerVersion(); // returns a JavaScript object
    var majorVersion = playerVersion.major; // access the major, minor and release version numbers via their respective properties
    var container = $(flashDivId);
	var non_flash_container = $(alternateDivId);

    if (majorVersion < 7 || force_noflash) {
		// we don't have flash so get ride of div
        if (container) {
			container.hide();
		}	
        // and show the wrap_image instead
        if (non_flash_container) non_flash_container.show();
    }
    else {
        // we have flash show the BG
		show_flash_js = true;
        if (container) container.show();
    }
}

function passwordStrength(password, description_id, score_id)
{
	var desc = new Array();
	desc[0] = "Very Weak";
	desc[1] = "Weak";
	desc[2] = "Better";
	desc[3] = "Medium";
	desc[4] = "Strong";
	desc[5] = "Strongest";

	var score   = 0;

	//if password bigger than 6 give 1 point
	if (password.length > 6) score++;

	//if password has both lower and uppercase characters give 1 point	
	if ( ( password.match(/[a-z]/) ) && ( password.match(/[A-Z]/) ) ) score++;

	//if password has at least one number give 1 point
	if (password.match(/\d+/)) score++;

	//if password has at least one special caracther give 1 point
	if ( password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) )	score++;

	//if password bigger than 12 give another 1 point
	if (password.length > 12) score++;

	$(description_id).innerHTML = desc[score];
	$(score_id).className = "strength" + score;
}

// scroll the element vertically based on its width and the slider maximum value
function scrollVertical(value, element, slider) {
	element.scrollTop = Math.round(value/slider.maximum*(element.scrollHeight-element.offsetHeight));
}
// used to resize the iframe'd lighwindow after the fact...
function resize_in_parent(frameId, size){
	try{
		frame = window.parent.document.getElementById(frameId);
		objToResize = (frame.style) ? frame.style : frame;
		objToResize.height = size;
	}
	catch(err){}
}


function hide_all(selector){
	$$(selector).each(function(link){
		link.hide();
	});
}

function numbersonly( e )  {
    var unicode = e.charCode ? e.charCode : e.keyCode;
    
    //if the key isn't the backspace key (which we should allow)
    if (unicode != 8) {
        //if not a number
        if (unicode < 48 || unicode > 57) {
            //disable key press
            return false;
        } else {
            // enable keypress
            return true;
        }//end else
    } else {
        // enable keypress
        return true;
    }//end else
}

function newAlbumHandler(selectElementId, showElementId){
    var val = $(selectElementId).value;
    
    if (val == '-1')
	 	{ $(showElementId).show(); }
    else 
		{ $(showElementId).hide(); }
}


function albumSelectHandler(selectElementId){
    var val = $(selectElementId).value;
    $('album_container').select('div.select-album').invoke('hide');
    $('album_' + val).show(); 
}


function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
	    return document[movieName];
	}
}

function show_album_military(album_id) {
	if (show_flash_js) {
		loadAlbum(album_id, 0);
	} else {
		if ($('non-flash-album-' + album_id + '-0')) {
			// note this requires a hack in lightwindow.js
			// add the following line to _processLinks
			// Event.observe(link, 'show:link', this.activate.bindAsEventListener(this, link), false);
			$('non-flash-album-' + album_id + '-0').fire('show:link');
		} 
	}
	return;
}

function share_on_facebook() {
	u=location.href;
	t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

function share_on_twitter(fullname) {
	u=location.href;
	t=document.title;
	window.open('http://twitter.com/home?status=A Tribute to ' + fullname + ' '+encodeURIComponent(u));
	return false;
}

function resize_textbox(box_id, min_size) {
  	var box = $(box_id);
	if (box) {
		var str = box.value;
    	var cols = box.cols;
	    var linecount = 0;
	
    	$A(str.split("\n")).each( 
			function(l) { 
				if (l.length > cols) {
					linecount += Math.ceil((l.length + 1) / cols);
				} else {
					linecount += 1;
				}
			} 
		);
		
		if (!min_size) min_size = 2;
		
		if (linecount < min_size) {
			box.rows = min_size;
		} else {
			box.rows = linecount;			
		}

	}
}

function reset_story_button(button_id) {
	var button = null;
	if (button_id)
		button = $("stories-submit-button-" + button_id);
	else
		button = $("stories-submit-button-");
		
	if (button) 
		button.value = "Share \u2192";
}
