var jsonrpc = jQuery.Zend.jsonrpc( {url: "/json.php"} );
var loginId = "contactLoginLink";
var currentView = "login";
var loginForm;
var presetLogin = null;
var registerForm = 	'<form method="POST" onsubmit="return verifyRegister();"><div><div class="contactLoginLeft">E-mail</div><div class="contactLoginRight"><input id="contactRegisterEmail" type="text" name="" /></div><div class="contactLoginLeft">Password</div><div class="contactLoginRight"><input id="contactRegisterPassword" type="password" name="" /></div><div class="contactLoginLeft">Confirm Password</div><div class="contactLoginRight"><input id="contactRegisterConfirmPassword" type="password"/></div></div><input type="Submit" value="Register" /></form>';

$(document).ready( function() {
	loginForm = $("#contactLoginForm").html();
	$("#contactLoginClose").click(toggleContactLogin);
	$("#contactLoginForgotPassword").click(sendForgotPassword);
	$("#contactLoginType").click( toggleContactLoginView );
});

function verifyContactLogin(){
    var invalid = false
    if( !$("#contactLoginUsername").val() )
	invalid = true;
    if( !$("#contactLoginPassword").val() )
	invalid = true;
    if(!invalid)
            sendContactLogin();
    else jqDialog.notify("Login failed.");
    return false;
}

function verifyRegister(){
    var invalid = ""
    if( !$("#contactRegisterEmail").val() )
        invalid += "Please provide a valid e-mail address.<br />";
    if( !$("#contactRegisterPassword").val() )
        invalid += "You must provide a password.<br />";
    if( $("#contactRegisterPassword").val() != $("#contactRegisterConfirmPassword").val() )
        invalid += "Passwords do not match.<br />";
    if(invalid == "")
            sendRegister();
    else jqDialog.notify("Registration failed. Please correct the following:<br />"+invalid);
    return false;
}

function toggleContactLoginView(){
	if(currentView == "login")
		showRegisterView();
	else
		showLoginView();
}

function showLoginView() {
	$("#contactLoginForm").html(loginForm);
        $("#contactLoginTitle").html("Login");
        $("#contactLoginType").html("<a href='#'>Register</a>");
        currentView = "login";
}

function showRegisterView() {
	$("#contactLoginForm").html(registerForm);
	$("#contactLoginTitle").html("Register");
	$("#contactLoginType").html("<a href='#'>Login</a>");
	currentView = "register";
}

function toggleContactLogin() {
    if( $("#contactLoginContainer").is(":visible") )
            $("#contactLoginContainer").hide();
    else {
            $("#contactLoginContainer").show();
            $("#contactLoginContainer").center(true);
    }
}

function sendForgotPassword() {
	var email = "";
	if( $("#contactLoginUsername").val() )
		email = $("#contactLoginUsername").val();
	else if ( $("#contactRegisterEmail").val() )
		email = $("#contactRegisterEmail").val();

	jqDialog.prompt("Your password will be reset and sent to the following e-mail address.", email,
    			function(data) { sendForgotPasswordYes(data); }, // callback function for 'Yes'
			function() { } // callback function for 'NO' button
		);
}

function sendForgotPasswordYes(data) {
	var params = {
		action: "forgotPassword",
                variables: { email: data }
           };
	var result= jsonrpc.flexMainAction(params);
	if(result != null && result["success"]) {
        	jqDialog.notify("Your password has been reset and sent to your e-mail address.");
        } else
                jqDialog.notify("This e-mail address is not registered.", 5);
}

function setPassword(){
	var form = "You have successfully registered. Please set your password.<div><form onsubmit='return verifySetPassword();'><div class='contactLoginLeft'>Old Password</div><div class='contactLoginRight'><input type='password' /></div><div class='contactLoginLeft'>New Password</div><div class='contactLoginRight'><input type='password' /></div><div class='contactLoginLeft'>Confirm Password</div><div class='contactLoginRight'><input type='password' /></div><input type='Submit' value='Change Password' /></form></div>";
	jqDialog.notify(form);
	var params =  {
                    action: "setPassword" ,
                    variables: { username: $("#contactLoginUsername").val(),
                                 password: $("#contactLoginPassword").val() }
            };

}

function sendRegister() {
	var params = {
		action: "register",
		variables: { 	email: $("#contactRegisterEmail").val(),
				password: $("#contactRegisterPassword").val() }
	}
	var result = jsonrpc.flexMainAction(params);
	if(result != null && result["success"]) {
		presetLogin = {
		            action: "login" ,
		            variables: { username: result["email"],
                            password: result["password"] }
		};
		sendContactLogin();
        } else
                jqDialog.notify("This e-mail address is already registered. Please login or click 'forgot password?' to reset your password.");
}

function sendContactLogin(){
	var params = presetLogin;
    if(!params) {
    	params =  {
        	    action: "login" ,
	            variables: { username: $("#contactLoginUsername").val(),
        	                 password: $("#contactLoginPassword").val() }
	    };
    }
    var result = jsonrpc.flexMainAction(params);
    if (result["success"]) {
        isLoggedIn();
	if(presetLogin) 
		jqDialog.notify("Thank you for registering.",3);
	//if(presetLogin) setPassword();
    } else
    	jqDialog.notify( result["message"] );
    showLoginView();
    presetLogin = null;
}

function sendLogout() {
    var params = {
            action: "logout"
    }
    var result = jsonrpc.flexMainAction(params);
    if ( result["success"] ) {
            isLoggedOut();
    }
}

function setLoginId(value){
	loginId = value;
}

function isLoggedIn(){
    $("#contactLoginContainer").hide();
    $("#"+loginId).html("Logout");
    $("#"+loginId).unbind("click");
    $("#"+loginId).click( sendLogout );
    $("#contactLoginPassword").val("");
thisMovie("browser").loginResultFromJavaScript("true");
    //getFlashMovie("browser").loginResultFromJavaScript(true);
	//dumpProps(o);
	//thisMovie("browser").loginResultFromJavaScript("true");
}

function isLoggedOut() {
	$("#contactLoginContainer").hide();
	$("#"+loginId).html("Login");
	$("#"+loginId).unbind("click");
	$("#"+loginId).click( toggleContactLogin );
	$("#"+loginId).val("");
}

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

function dumpProps(obj, parent) {
   // Go through all the properties of the passed-in object
    for (var i in obj) {
          // if a parent (2nd parameter) was passed in, then use that to
                // build the message. Message includes i (the object's property name)
                      // then the object's property value on a new line
                            if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
                                  // Display the message. If the user clicks "OK", then continue. If they
                                        // click "CANCEL" then quit this level of recursion
                                              if (!confirm(msg)) { return; }
                                                    // If this property (i) is an object, then recursively process the object
                                                          if (typeof obj[i] == "object") {
                                                                   if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
                                                                         }
                                                                            }
                                                                            }

