$L.add('contactsLoginForm', new LContactsLoginForm());

function LContactsLoginForm()
{
    var obj = $L.object(this);

    obj._endpoint = "https://www.lulu.com/content/share/contacts_login.php";
    obj._$form = $jq('#ozform_login');
    obj._formData = {};
    obj._noticeTypes = {OK:{color:"green"}, FAIL:{color:"red"}};
    obj._invalidFieldsMsg = "The indicated fields are invalid.";
    obj._failureMsg = "The provided email and password do not match.";
    obj._emptyFieldsMsg = "Please fill in all fields.";

    obj.submit = function() {
        obj._$clearNotices();
        obj._$gatherDataFromInputs();
        if (obj._validateData()) {
            obj._$post();
        } else {
            obj._$insertNotice(obj._emptyFieldsMsg, obj._noticeTypes.FAIL);
        }
    };

    obj._validateData = function() {
        var allFilled = true;
        for (name in obj._formData) {
            if (typeof obj._formData[name] == 'undefined' || obj._formData[name] == "") {
            	obj._$highlightField(name);
                allFilled = false;
            }
        }
        return allFilled;
    };

    obj._$highlightField = function(name) {
    	var field = obj._$form.find('input[name="'+name+'"]').parent().find('label');
    	field.addClass('invalid');
    };

    obj._$gatherDataFromInputs = function() {
        obj._$form.find('input').each(function() {
            obj._formData[$jq(this).attr('name')] = $jq(this).val();
        });
    };

    obj._$insertNotice = function(msg, type) {
        $jq('#ozform_login_feedback').append($jq('<div>').css(type).text(msg));
    };

    obj._$clearNotices = function() {
        $jq('#ozform_login_feedback').empty();
        obj._$resetFieldHighlights();
    };

    obj._$disablePost = function() {
        obj._$form.find("input[name='ozbtn_login']").attr('disabled', true).addClass('buttonDisabled');
    };

    obj._$enablePost = function() {
        obj._$form.find("input[name='ozbtn_login']").attr('disabled', false).removeClass('buttonDisabled');
    };

    obj._$resetFieldHighlights = function() {
        obj._$form.find('label').removeClass('invalid');
    };

    obj._$post = function() {
        obj._$disablePost();
        var options = {
            cache: false,
            url: obj._endpoint,
            type: 'POST',
            data: obj._formData,
            dataType: 'json',
            success: obj._handleResponse,
            error: obj._ajaxErr
        }
        var request = $jq.ajax(options);
    };

    obj._handleResponse = function(response) {
        if (response.success) {
        	$jq('#ozpanel_loginpassword').css('display', 'none');
        	$L.contactsSelectForm.setContacts(response.contacts);
        	$jq('#contacts_select').css('display', 'block');
        } else if (typeof response.invalidFields != 'undefined' && response.invalidFields.length > 0) {
            obj._$clearNotices();
            obj._$highlightFields( response.invalidFields );
            obj._$insertNotice(obj._invalidFieldsMsg, obj._noticeTypes.FAIL);
        } else {
            obj._$clearNotices();
            obj._$insertNotice(obj._failureMsg, obj._noticeTypes.FAIL);
        }
        obj._$enablePost();
    };

    obj._ajaxErr = function(XMLHttpRequest, textStatus, errorThrown) {
        obj._$clearNotices();
        obj._$insertNotice(obj._failureMsg, obj._noticeTypes.FAIL);
        obj._$enablePost();
    };

    return obj;
}
$L.add('contactsSelectForm', new LContactsSelectForm());

function LContactsSelectForm()
{
    var obj = $L.object(this);

    obj._$form = $jq('#contacts_select_form');
    obj._emails = new Array();

    obj.setContacts = function(contacts) {
    	$jq('#contacts_select_form_emails').empty();
    	for (index in contacts) {
    		$jq('#contacts_select_form_emails').prepend('<input type="checkbox" value="' + contacts[index].email + '">' + contacts[index].email + '</input><br>');
    	}
    }

    obj.selectAll = function() {
    	var checked = $jq('#contacts_select_all').attr('checked') ? true : false;
    	$jq('#contacts_select_form_emails').find('input').attr('checked', checked); 
    }

    obj.submit = function() {
        obj._gatherEmails();
        if (obj._emails.length) {
        	$L.emailFriendForm.addEmails(obj._emails);
        	obj.restart();
        }
    };

    obj.restart = function() {
    	$jq('#contacts_select').css('display', 'none');
    	ozStartAgain();
    	$jq('#ozpanel_loginpassword').css('display', 'block');
    }

    obj._gatherEmails = function() {
        obj._emails = new Array();
    	$jq('#contacts_select_form_emails').find('input:checked').each(function() {
            obj._emails.push($jq(this).val());
        });
    };

    return obj;
}
$L.add('emailFriendForm', new LEmailFriendForm());

function LEmailFriendForm ( ) {
    var obj = $L.object(this);
    
    obj._token = "NULLTOKEN";
    obj._endpoint = "http://www.lulu.com/content/share/email.php";
    obj._$form = $jq('#email_form');
    obj._formData = {fToken: obj._token};
    obj._noticeTypes = {OK:{color:"green"}, FAIL:{color:"red"}};
    obj._successMsg = "A note has been sent to ";
    obj._invalidFieldsMsg = "The indicated fields are invalid.";
    obj._failureMsg = "Sorry, your note could not be sent.";
    obj._emptyFieldsMsg = "Please fill in all fields.";
    
    obj.submit = function ( ) {
        obj._$clearNotices();
        obj._$gatherDataFromInputs();
        if (obj._validateData()) {
            obj._$post();
        } else {
            obj._$insertNotice(obj._emptyFieldsMsg, obj._noticeTypes.FAIL);
        }
    };   

    obj.addEmails = function(emails) {
		var _$emails = obj._$form.find("textarea[name='recipientEmail']");
    	for (index in emails) {
    		if (_$emails.val().length > 0) {
	    		_$emails.val(_$emails.val() + ', ');
    		}
    		_$emails.val(_$emails.val() + emails[index]);
    	}
    }
    
    obj.reset = function() {
        obj._$form.find("input[name='recipientName']").val("Friends");
        obj._$form.find(":input[name='recipientEmail']").val("");
        obj._$clearNotices();
    };
    
    obj._validateData = function ( ) {
        var allFilled = true;
        for ( fieldName in obj._formData ) {
            if ( typeof obj._formData[fieldName] == 'undefined' || obj._formData[fieldName] == "") {
            	obj._$highlightField(fieldName);
                allFilled = false;
            }
        }
        return allFilled;
    };

    obj._$gatherDataFromInputs = function ( ) {
        obj._$form.find('input').add('textarea')
            .each(function() {
                obj._formData[$jq(this).attr('name')] = $jq(this).val();
            });
    };

    obj._$insertNotice = function ( msg, type ) {
        $jq('#email_friend_form_feedback')
            .append(
                $jq('<div>')
                    .css(type)
                    .text(msg)
                );
    };

    obj._$clearNotices = function ( ) {
        $jq('#email_friend_form_feedback').empty();
        obj._$resetFieldHighlights();
    };

    obj._$disablePost = function ( ) {
        obj._$form.find("input[name='fSubmit']").attr('disabled', true).addClass('buttonDisabled');
    };

    obj._$enablePost = function ( ) {
        obj._$form.find("input[name='fSubmit']").attr('disabled', false).removeClass('buttonDisabled');
    };

    obj._$highlightFields = function(fieldNames) {
        for (var i=0; i < fieldNames.length; i++) {
        	obj._$highlightField(fieldNames[i]);
        }
    };

    obj._$highlightField = function(name) {
    	obj._$form.find(':input[name="'+name+'"]').parent().find('label').addClass('invalid');
    };

    obj._$resetFieldHighlights = function ( ) {
        obj._$form.find('label').removeClass('invalid');
    };

    obj._$post = function ( ) {
        obj._$disablePost();
        $jq.ajax({
            cache: false, 
            url: obj._endpoint, 
            type: 'POST', 
            data: obj._formData, 
            dataType: 'json',
            success: obj._handleResponse, 
            error: obj._ajaxErr 
            });
    };

    obj._handleResponse = function ( response ) {
        if (response.success) {
            obj.reset();
            obj._$insertNotice(obj._successMsg+obj._formData.recipientName , obj._noticeTypes.OK);
        } else if (typeof response.invalidFields != 'undefined' && response.invalidFields.length > 0) {
            obj._$clearNotices();
            obj._$highlightFields( response.invalidFields );
            obj._$insertNotice(obj._invalidFieldsMsg, obj._noticeTypes.FAIL);
        } else {
            obj._$clearNotices();
            obj._$insertNotice(obj._failureMsg, obj._noticeTypes.FAIL);
        }
        obj._$enablePost();
    };

    obj._ajaxErr = function ( XMLHttpRequest, textStatus, errorThrown ) {
        obj._$clearNotices();
        obj._$insertNotice(obj._failureMsg, obj._noticeTypes.FAIL);
        obj._$enablePost();
    };

    return obj;
}
