function doSubmit( e )
{
  var keyCode = (window.Event) ? e.which : e.keyCode;
  if( keyCode == 13 ) document.forms[0].elements[4].click();
}

var SPI = {
	
	GET_STARTED_URL: '/get-started/',
	
	init:
		function() {
			$('#login-form').submit(SPI.ajaxLogin);
		},
		
	ajaxLogin:
		function(event) {
			event.preventDefault();
			
			$('#form-submit').attr('disabled', true);
			$('#spinner').show();
			
			$('#id_email').removeClass('warn');
			$('#id_password').removeClass('warn');
			
			var action = $('#login-form').attr('action');
			var postString = 'email='+ $('#id_email').val() +
							 '&password='+ $('#id_password').val() +
							 '&remember='+ $('#id_remember').val();
			
			var ajaxOptions = {
					   type: "POST",
					   url: action,
					   data: postString,
					   success: SPI.loginResult
			};
			
			$.ajax(ajaxOptions);

		},
		
	loginResult:
		function(responseStr) {
			
			eval('var response='+ responseStr);
			
			var isSuccess = response.login;
			if (isSuccess) {
				SPI.nextPage(response.success_url);
			}
			else {
				// TODO: make below have more accurate response
			    $('#form-errors').html('Invalid login');
				$('#spinner').hide();
				$('#form-submit').attr('disabled', false);
				
				for (var field in response) {
					if (field == 'login') {
						continue;
					}
					else if (field == '__all__') {
						$('#form-errors').html('Invalid login');
					}
					else {
						$('#id_'+ field).addClass('warn');
					}
				}

			}
		},
		
	nextPage:
		function(url) {
			window.location = url;
			/*
			//Shadowbox is a modal popup like lightbox
			Shadowbox.open({
		        content:    url,
		        player:     "iframe",
		        title:      "Sprowtt - Get Started",
		        height:     700,
		        width:      800
		    });
		    */			
		}
}

$( SPI.init );

var SP = {

	init:
		function() {

			$('#close_alerts').click(
					function(event) {
						event.preventDefault();
						$('.alerts').hide();
					}
			);

			$('#feedback-input').one( 'click', function() {$(this).val('')} );
			$('#search-input').one( 'click', function() {$(this).val('')} );
			$('#mail-input').one( 'click', function() {$(this).val('')} );
			$('#password-input').one( 'click', function() {$(this).val('')} );
		}
}

$(SP.init);

function rot(t){
	return t.replace(/[a-zA-Z]/g, function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);});
}

// Django Admin Forms version of Multiple Select Widget

// Handles related-objects functionality: lookup link for raw_id_fields
// and Add Another links.

function html_unescape(text) {
    // Unescape a string that was escaped using django.utils.html.escape.
    text = text.replace(/&lt;/g, '<');
    text = text.replace(/&gt;/g, '>');
    text = text.replace(/&quot;/g, '"');
    text = text.replace(/&#39;/g, "'");
    text = text.replace(/&amp;/g, '&');
    return text;
}

// IE doesn't accept periods or dashes in the window name, but the element IDs
// we use to generate popup window names may contain them, therefore we map them
// to allowed characters in a reversible way so that we can locate the correct 
// element when the popup window is dismissed.
function id_to_windowname(text) {
    text = text.replace(/\./g, '__dot__');
    text = text.replace(/\-/g, '__dash__');
    return text;
}

function windowname_to_id(text) {
    text = text.replace(/__dot__/g, '.');
    text = text.replace(/__dash__/g, '-');
    return text;
}

function showRelatedObjectLookupPopup(triggeringLink) {
    var name = triggeringLink.id.replace(/^lookup_/, '');
    name = id_to_windowname(name);
    var href;
    if (triggeringLink.href.search(/\?/) >= 0) {
        href = triggeringLink.href + '&pop=1';
    } else {
        href = triggeringLink.href + '?pop=1';
    }
    var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
    win.focus();
    return false;
}

function dismissRelatedLookupPopup(win, chosenId) {
    var name = windowname_to_id(win.name);
    var elem = document.getElementById(name);
    if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
        elem.value += ',' + chosenId;
    } else {
        document.getElementById(name).value = chosenId;
    }
    win.close();
}

function showAddAnotherPopup(triggeringLink) {
    var name = triggeringLink.id.replace(/^add_/, '');
    name = id_to_windowname(name);
    href = triggeringLink.href
    if (href.indexOf('?') == -1) {
        href += '?_popup=1';
    } else {
        href  += '&_popup=1';
    }
    var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
    win.focus();
    return false;
}

function dismissAddAnotherPopup(win, newId, newRepr) {
    // newId and newRepr are expected to have previously been escaped by
    // django.utils.html.escape.
    newId = html_unescape(newId);
    newRepr = html_unescape(newRepr);
    var name = windowname_to_id(win.name);
    var elem = document.getElementById(name);
    if (elem) {
        if (elem.nodeName == 'SELECT') {
            var o = new Option(newRepr, newId);
            elem.options[elem.options.length] = o;
            o.selected = true;
        } else if (elem.nodeName == 'INPUT') {
            elem.value = newId;
        }
    } else {
        var toId = name + "_to";
        elem = document.getElementById(toId);
        var o = new Option(newRepr, newId);
        SelectBox.add_to_cache(toId, o);
        SelectBox.redisplay(toId);
    }
    win.close();
}

