// ------------------------------------------------------------------------------------------------------------------
// -- litevite import contacts --
// ------------------------------------------------------------------------------------------------------------------


function applyPasswordKeypress(event) {
    if (event.keyCode == 188 || event.keyCode == Event.KEY_RETURN) {
    	contactsClickGo();
    }
}


function contactsClickGo() {
    // let's hide any error fields first to get back to known state
    $('email-validation-message').hide();


    if (validateEmailCredentials()) {
        $('webmail-working-section').show();
        doEmailContactsImport();
    }
}


function validateEmailCredentials() {

    // shake field and show form error
    if (validateEmail($F('email-address-input'), false, null) == false) {
        $('email-validation-message').update("Incorrect email address format");
        $('email-validation-message').show();
        new Effect.Shake('email-address-input');
        return false;
    }

    // shake field and show form error
    if ($F('email-password-input').length <= 0) {
        $('email-validation-message').update("Please specify a password");
        $('email-validation-message').show();
        new Effect.Shake('email-password-input');
        return false;
    }

    if ($('email-service-select').value == 'select') {
        $('email-validation-message').update("Please choose an email service");
        $('email-validation-message').show();
        new Effect.Shake('email-service-select');
        return false;
    }
    return true;

}

function refreshContactsCounts(importedContactsCount, totalContactsCount) {
	$('tab-invite-contacts-count').update('<small>' + totalContactsCount + ' contacts</small>');
	$('import-contacts-count').update('You have ' + totalContactsCount + ' contacts');
	
	
}

function showMessage(text, elementId) {
        var element = $(elementId);
        element.update(text);
        new Effect.Appear(element, { queue: 'front', duration: .5 });
    }


function addressBookClickGo() {
    // hide any error fields
    $('contacts-file-validation').hide();

    // shake field and show form error
    if ($F('contacts-file-input').length <= 0) {
        $('contacts-file-validation').update("Please select a file");
        $('contacts-file-validation').show();
        new Effect.Pulsate('contacts-file-input', { pulses: 2, duration: 0.5 });
        return false;
    }

    if ($F('file-type-select') == 'select') {
        $('contacts-file-validation').update("Please select a file type");
        $('contacts-file-validation').show();
        new Effect.Shake('file-type-select');
        return false;
    }

    $('address-book-working-section').show();

    // magic yahoo method to allow asynch upload
    YAHOO.util.Connect.setForm('contacts-upload-form', true);

    // this little section handles the response from the photo upload
    var uploadHandler = {
        upload: function(o) {
            stopUpload();
        }
    };

    YAHOO.util.Connect.asyncRequest('POST', '/ajax2/email-contacts-file-upload.iggli', uploadHandler);

}


function stopUpload() {
    // the file has finished uploading, hit the server again and get status
    new Ajax.Request('/ajax2/email-get-contact-upload-status.iggli', {
        method:'get',
		evalJSON: 'force',
		
        onSuccess:function(transport) {
            
            // stop the spinner
            $('address-book-working-section').hide();
				//alert("success: " + transport.responseText);
	        	var json, message;
	        	try {
	            	
		        	json = transport.responseJSON;

		        	if (json.responseCode) {
		        		
			            if (json.responseCode == 200) {
                            //alert('ok');
                            initAutocomplete();
			            } else {
			            	showMessage(json.message, 'contacts-file-validation');
			            }
			            
		        	} else {
		            	displayMessage("ERROR: " + json.message, "error");
			        }
		        	
		        	if (json.elements) {
		        		
		        		if (json.elements.importedContactsMessage) {
		        			showMessage(json.elements.importedContactsMessage, 'contacts-file-validation');
		        		}
		        		if (json.elements.importedContactsCount && json.elements.totalContactsCount) {
		        			refreshContactsCounts(json.elements.importedContactsCount, json.elements.totalContactsCount);
		        		}
		        		
		        	}
		        } catch(err) {
		        	alert(err);
		        	displayMessage("CAUGHT ERROR: " + transport.responseText, "error");
		        }  
            
            
        },

        onFailure:function(transport) {
            // 327 is returned by our server, when, in a special Safari browser case where the hidden iframe
            // onload method fires when the parent page (email tab) is loaded, which causes a NPE
            // on the server, we trap this and return 327, which should NOT do anything
            if (transport.status != 0) {
                // stop the spinner
                $('address-book-working-section').hide();
                showMessage(transport.responseText, 'contacts-file-validation')
            }
        },
        onComplete:function(transport) {
        }

    });

    return false;
}

function doEmailContactsImport() {

    // import the contacts and return an FTL section with the imported count, or error
    new Ajax.Request('/ajax2/litevite-import-email-contacts.iggli', {
        method:'post',
        evalJSON: 'force',
        parameters: {
            emailAddressInput: $('email-address-input').value,
            emailPasswordInput: $('email-password-input').value,
            emailServiceSelect: $('email-service-select').value
        },

        onSuccess:function(transport) {
            // stop the spinner
            $('webmail-working-section').hide();
				//alert("success: " + transport.responseText);
	        	var json, message;
	        	try {
	            	
		        	json = transport.responseJSON;

		        	if (json.responseCode) {
		        		
			            if (json.responseCode == 200) {
                            //alert('ok');
                            initAutocomplete();
			            } else {
			            	showMessage(json.message, 'email-validation-message');
			            }
			            
		        	} else {
		            	displayMessage("ERROR: " + json.message, "error");
			        }
		        	
		        	if (json.elements) {
		        		
		        		if (json.elements.importedContactsMessage) {
		        			showMessage(json.elements.importedContactsMessage, 'email-validation-message');
		        		}
		        		if (json.elements.importedContactsCount && json.elements.totalContactsCount) {
		        			refreshContactsCounts(json.elements.importedContactsCount, json.elements.totalContactsCount);
		        		}
		        		
		        	}
		        } catch(err) {
		        	alert(err);
		        	displayMessage("CAUGHT ERROR: " + transport.responseText, "error");
		        }  
        },

        onFailure:function(transport) {
            // stop the spinner
            $('webmail-working-section').hide();
            displayMessage(transport.responseText);  
        },
        
        onComplete:function(transport) {
        }

    });
}
