$(document).ready(function() {
	$(".link_to_med").lightBox();

	// Add lightBox to all the links and find the first one and then click() the first one to start it
	$("#start_lightbox").click(function() {
		$(".link_to_med:first").click();
		return false;
	});

	if ($.getUrlVar('lightbox')) {
		$(".link_to_med:first").click();
	}

	init_keyboard_nav();
	init_quick_tag();
});

function init_quick_tag() {
	var mapping = get_tag_words();
	init_cheat_sheet(mapping);

	$("#tags").keydown(function(e) {
		var mapping = get_tag_words();
	
		var num = e.which;
		var chr = String.fromCharCode(num);

		//return true;

		// Alt key
		if (num == 18) {
			$("#cheat_sheet").toggle();
			return true;
		// ESC
		} else if (num == 27) {
		// Return/Enter
		} else if (num == 13) {
			return true;
		}

		//alert(num);

		// Backspace
		if (num == 8 || num == 46) {
			$("#tags").val('');
			return false;
		}

		var opts = find_word(chr,mapping);
		var word = opts[0];
		var remove = opts[1];

		if (!word) { return false; }

		//console.log("%s: %s",chr,word);

		var current_words = $("#tags").val();
		var words = new Array();

		if (current_words) {
			words = current_words.split(/\W+/);
		}

		words.push(word.toLowerCase());

		console.log("Adding: ", word);
		console.log("Removing: ", remove, " from " , words);

		words = array_diff(words,remove);

		words = words.sort();
		words = array_unique(words);

		// Backspace
		if (num == 8 || num == 46) {
			alert('bs');
			//words = ('none');
			//$("#tags").css('background-color','red');
		}

		if (words) {
			$("#tags").val(words.join(", "));
		}

		return false;
	});
}

var key_pressed = new Object;
function find_word(letter,mapping) {
	var words = mapping[letter];
	if (!words) { return ''; }
	words = words.split(/\W+/);

	if (!key_pressed[letter]) { key_pressed[letter] = 0; }
	
	var num = key_pressed[letter] % words.length;
	var word = words[num];
	var remaining = new Array();

	for (i in words) {
		if (words[i] != word) {
			remaining.push(words[i].toLowerCase());
		}
	}

	key_pressed[letter]++;

	return [word,remaining];
}

function init_cheat_sheet(mapping) {
	var keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	$("#cheat_sheet").remove();

	var h = "<div id=\"cheat_sheet\" style=\"border: 1px solid;\">\n"

	for (i in keys) {
		var letter = keys[i];
		var word = mapping[letter];
		if (!word) { word = ''; }
		h += "<div class=\"letter\" style=\"font-size: 0.7em;\">" + letter + ": " + word + "</div>\n"; 
	}
	h += "</div>\n"

	h = $(h);
	h.css('position','absolute');
	h.css('top','10px');
	h.css('left','10px');
	h.hide();

	$("body").append(h);

	$(".letter").click(function() {
		var mytext= $(this).text();	
		var match = mytext.match(/(\w): (.*)/);

		letter = match[1];
		words = match[2];

		var input = prompt("What should " + letter + " map to?", words);

		if (input) { 
			update_tag_words(letter,input);

			$("#tags").focus();
		}
	});
}

function update_tag_words(letter,word) {
	letter = letter.toUpperCase();
	var mapping = get_tag_words();

	mapping[letter] = word;

	var json = JSON.stringify(mapping);
	$.cookie('cheat_keys',json, { expires: 90 });

	init_cheat_sheet(get_tag_words());
}

function get_tag_words() {
	var data = $.cookie('cheat_keys');
	var mapping = new Object();

	if (data) { 
		mapping = JSON.parse(data); 
	} else {
		// Default if no cookie
		mapping['G'] = "Gabe";
		mapping['S'] = "Scott";
		mapping['A'] = "Angela";
		mapping['R'] = "Roland";
		mapping['B'] = "Beach";
		mapping['J'] = "Jason";
	}

	return mapping;
}

function init_keyboard_nav() {
	$(window).keypress(function(e) {
		var code = e.charCode;

		// 32 = space
		// 110/78 = n/N
		if (code == 32 || code == 110 || code == 78) {
			var url = $("#next_image").attr('href');
			var input_has_focus = $("input:focus").length > 0;

			// Don't change the url if you're in a textbox typing in a caption
			if (url && !input_has_focus) { location.href = url; }
		// 112/80 = p/P
		} else if (code == 112 || code == 80) {
			var url = $("#previous_image").attr('href');
			var input_has_focus = $("input:focus").length > 0;

			// Don't change the url if you're in a textbox typing in a caption
			if (url && !input_has_focus) { location.href = url; }
		}
	});
}

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

function array_unique (inputArr) {
    var key = '',
        tmp_arr2 = {},
        val = '';

    var __array_search = function (needle, haystack) {
        var fkey = '';
        for (fkey in haystack) {
            if (haystack.hasOwnProperty(fkey)) {
                if ((haystack[fkey] + '') === (needle + '')) {
                    return fkey;
                }
            }
        }
        return false;
    };

    for (key in inputArr) {
        if (inputArr.hasOwnProperty(key)) {
            val = inputArr[key];
            if (false === __array_search(val, tmp_arr2)) {
                tmp_arr2[key] = val;
            }
        }
    }

    return array_values(tmp_arr2);
}

function array_values (input) {
    var tmp_arr = [],
        key = '';

    if (input && typeof input === 'object' && input.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array
        return input.values();
    }

    for (key in input) {
        tmp_arr[tmp_arr.length] = input[key];
    }

    return tmp_arr;
}

function array_remove(needle,haystack) {
	var filtered_array = new Array();

	for (i in haystack) {
		var item = haystack[i];

		if (item != needle) {
			filtered_array.push(item);
		}
	}

	return filtered_array;
}

jQuery.cookie = function (key, value, options) {
    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

function array_diff (arr1) {
    var retArr = {},
        argl = arguments.length,
        k1 = '',
        i = 1,
        k = '',
        arr = {};

    arr1keys: for (k1 in arr1) {
        for (i = 1; i < argl; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (arr[k] === arr1[k1]) {
                    // If it reaches here, it was found in at least one array, so try next value
                    continue arr1keys;
                }
            }
            retArr[k1] = arr1[k1];
        }
    }

    return array_values(retArr);
}

