if (typeof(Collactive) == 'undefined') {
	Collactive = {};
}

Collactive.AssistantUI = function(wizard, siteShortName, siteName, siteAgreeLine, feedShortName, feedName, hasLogo) {
    this._wizard = wizard;
	this._siteName = siteName ? siteName : "this site";
	this._siteAgreeLine = siteAgreeLine ? siteAgreeLine : "";
	this._siteUsernameField = "Username";

    if (hasLogo) {
    	if (siteShortName) {
    		this._siteLogo = "http://" + document.location.host + "/images/assistant/" + siteShortName + "_logo.gif";
    	}

    	if (feedShortName) {
    		this._feedLogo = "http://" + document.location.host + "/images/groups/" + feedShortName + "/assistant_logo.gif";
    	}
    }

	this._feedName = feedName;

    // Set the name of the username field (e.g. if it is login by email)
    this.setUsernameField = function(usernameField) {
        this._siteUsernameField = usernameField;
    };

    // Display the form
    this.displayForm = function(fields, fieldsMetadata, callbacks, extraContent) {
        this._wizard.displayForm('Open an account on <font color="black">' + this._siteName + '</font>',
                                 'Please provide some information in order to set up an account.',
                                 this._siteLogo,
                                 fields, fieldsMetadata, callbacks.onCompletion,
                                 Collactive.bind(this, function() {
                                    if (confirm("Are you sure you'd like to close Collactive Web Assistant?")) {
                                        this.hideUI();
                                        Collactive.CSAUtils.notifyOperation("assist_no_form_filling");
                                        callbacks.onCancel();
                                    }
                                    }),
                                 extraContent);
    };


    // Display a prompt asking the user if he'd like to add his existing account
    this.displayAccountAddPrompt = function(addFromRegister, failedLastTime, username, callback) {
        Collactive.CSAUtils.notifyOperation("assist_add_prompt");

        if (username == null) {
            username = "";
        }

        var fieldsMetadata = {
    		username: {
                prompt: this._siteUsernameField,
                errorString: ""
            },
            password1: {
                prompt: "Enter password",
                input: '<input id="collactive_wizard_form_password1" type="password" autocomplete="off" style="width: 220px"/>',
                validate: function() {
                    var p1 = Collactive.DomUtils.gEBI("collactive_wizard_form_password1").value;
                    var p2 = Collactive.DomUtils.gEBI("collactive_wizard_form_password2").value;

                    return (p1 != "" && (p1 == p2));
                },
                errorString: "Please enter your password here and below"
            },
            password2: {
                prompt: "Confirm password",
                input: '<input id="collactive_wizard_form_password2" type="password" autocomplete="off" style="width: 220px"/>',
                validate: function() {
                    var p1 = Collactive.DomUtils.gEBI("collactive_wizard_form_password1").value;
                    var p2 = Collactive.DomUtils.gEBI("collactive_wizard_form_password2").value;

                    return (p1 != "" && (p1 == p2));
                },
                errorString: "Please enter your password here and above"
            }
        };

        var h = [];
        h[h.length] = '<div style="margin: 30px 0px; font-size: 12px">';
        h[h.length] = '  <a href="#" onclick="registerNewAccount(); return false;">I\'d like to register a new account</a>';
        h[h.length] = '</div>';
        window.registerNewAccount = Collactive.bind(this, function() {
            Collactive.CSAUtils.notifyOperation("assist_add_new_account");
            callback.onRegisterNew();
        });

        var subtitle = "";
        if (addFromRegister) {
            subtitle = 'You appear to already have an account on ' + this._siteName
                       + '. If you\'d like to use it, please provide the following details.';
        } else if (failedLastTime) {
            subtitle = '<b>Sorry, your username and password were not accepted by ' + this._siteName + '.</b>';
        } else {
            subtitle = 'Collactive Web Assistant can use your existing account - just provide the following details.'
        }

        subtitle += "<br><br>";

        this._wizard.displayForm('Register an existing <font color="black">' + this._siteName + '</font> account',
                                 subtitle,
                                 this._siteLogo, {
                                    "username": username,
                                    "password1": "",
                                    "password2": ""
                                 },
                                 fieldsMetadata,
                                 Collactive.bind(this, function() {
                                     Collactive.CSAUtils.notifyOperation("assist_add_ok");
                                     callback.onSuccess(Collactive.DomUtils.gEBI("collactive_wizard_form_username").value,
                                                        Collactive.DomUtils.gEBI("collactive_wizard_form_password1").value);
                                 }),
                                 Collactive.bind(this, function() {
                                    if (confirm("Are you sure you'd like to close Collactive Web Assistant?")) {
                                        this.hideUI();
                                        Collactive.CSAUtils.notifyOperation("assist_no_add");
                                        callback.onCancel();
                                    }
                                 }),
                                 h.join("")
                                 );
    };


    // Display a prompt asking the user to enter the confirmation URL
    this.displayConfirmationPrompt = function(fromAddress, confirmMatch, callback) {
        Collactive.CSAUtils.notifyOperation("confirm_wait_prompt");

        var fieldsMetadata = {
    		confirmURL: {
                prompt: "Confirmation link",
                errorString: "Please enter the link as it appears in the email",
                validate: confirmMatch
            }
        };

        this._wizard.displayForm('Confirm your <font color="black">' + this._siteName + '</font> account',
                                 this._siteName + " has sent you an email to confirm your address.<br><br>"
                                                + "Please open your email inbox, find a message from <b>" + fromAddress
                                                + "</b>,<br>copy the confirmation link inside and paste it here.<br><br>"
                                                + "<b>Please DO NOT click the confirmation link directly!</b>"
                                                + "<br>",
                                 this._siteLogo, ["confirmURL"],
                                 fieldsMetadata,
                                 Collactive.bind(this, function() {
                                     Collactive.CSAUtils.notifyOperation("assist_confirm_given");
                                     callback.onSuccess(Collactive.DomUtils.gEBI("collactive_wizard_form_confirmURL").value);
                                 }),
                                 Collactive.bind(this, function() {
                                    if (confirm("Are you sure you'd like to close Collactive Web Assistant?")) {
                                        this.hideUI();
                                        Collactive.CSAUtils.notifyOperation("assist_no_confirm");
                                        callback.onCancel();
                                    }
                                 }));
    };


    // Display a prompt asking the user if he'd like to register
    this.displayAccountSetupPrompt = function(cb) {
        Collactive.CSAUtils.notifyOperation("assist_setup_prompt");

        var m = [];
        m[m.length] = '<div style="margin: 40px 0px; font-size: 13px">';
        m[m.length] = '  <a target="_new" href="http://www.collactive.com/webassistant.html">Click here</a> to learn more about Collactive Web Assistant</a>';
        m[m.length] = '</div>';

        m[m.length] = '<div style="margin: 40px 0px; font-size: 13px">';
        m[m.length] = '  <b>' + this._siteAgreeLine + '</b>';
        m[m.length] = '</div>';

        m[m.length] = '<div style="margin: 40px 0px; font-size: 12px">';
        m[m.length] = '  <a href="#" onclick="addExistingAccount(); return false;">I\'d like to use an existing account</a>';
        m[m.length] = '</div>';

        window.addExistingAccount = Collactive.bind(this, function() {
            Collactive.CSAUtils.notifyOperation("assist_setup_existing");
            cb.onUseExisting();
        });

        this._wizard.displayContent('Open an account on <font color="black">' + this._siteName + '</font>',
                            this._siteName + ' requires you to open an account in order to participate.<br>Collactive Web Assistant will help you open your account in just a few clicks.',
                            this._siteLogo,
                            m.join(""),
                            [["Set up an account", Collactive.bind(this, function() {
                                this.displayLoadingMessage();
                                Collactive.CSAUtils.notifyOperation("assist_setup_account");
            	   	   		    cb.onSetupAccount();
                              })]],
                            [["Cancel", Collactive.bind(this, function() {
                                    if (confirm("Are you sure you'd like to close Collactive Web Assistant?")) {
                                    this.hideUI();
                                    Collactive.CSAUtils.notifyOperation("assist_no_setup_account");
                			     	cb.onNoWallet();
                                }
                            })]]
                            );
    };

    this.displayVerificationImagePrompt = function(missedLastTime, imageHTML, cb) {
        var m = [];
        m[m.length] = '<div style="margin-top: 40px" align="center">';
        m[m.length] = '  <table cellspacing="0" cellpadding="0">';
        m[m.length] = '    <tr>';
        m[m.length] = '      <td align="center" style="padding-bottom: 30px; font-size: 11px">';
        m[m.length] = imageHTML;
        m[m.length] = '      </td>';
        m[m.length] = '    </tr>';
        m[m.length] = '    <tr>';
        m[m.length] = '      <td>';
        m[m.length] = '        <table cellspacing="0" cellpadding="0">';
        m[m.length] = '          <tr>';
        m[m.length] = '            <td class="collactive_wizard_form_label">';
        m[m.length] = '              Enter the text in the image:';
        m[m.length] = '           </td>'
        m[m.length] = '           <td class="collactive_wizard_form_input">';
        m[m.length] = '             <input id="collactive_verification_code" type="text" autocomplete="off" style="width: 220px"/>';
        m[m.length] = '           </td>'
        m[m.length] = '          </tr>';
        m[m.length] = '        </table>';
        m[m.length] = '      </td>';
        m[m.length] = '    </tr>';
        m[m.length] = '  </table>';
        m[m.length] = '</div>';

        var msg = missedLastTime
            ? "<b>Sorry, the text you typed was not correct!</b>"
            : ('<b>' + this._siteName + '</b> needs to verify that you are human.');
        this.displayContent('Image Verification', msg + '<br>Please type the text you see in the image below.',
                            this._siteLogo, m.join("\n"),
                            [["Next", Collactive.bind(this, function() {
                                Collactive.CSAUtils.notifyOperation("assist_submit_captcha");
                                var code = Collactive.DomUtils.gEBI('collactive_verification_code').value;
            	   	   		    cb.onCodeSubmission(code);
                              })]],
                            cb.onCodeCancel ? [["Cancel", Collactive.bind(this, function() {
                                    if (confirm("Are you sure you'd like to close Collactive Web Assistant?")) {
                                    this.hideUI();
                                    Collactive.CSAUtils.notifyOperation("assist_no_captcha");
                                    cb.onCodeCancel();
                                }
                                })]] : null
                            );
    };

    this.displayThumbChoosePrompt = function(thumbHTMLs, cb) {
        var m = [];
        m[m.length] = '<div style="margin-top: 5px; width:440px; height:140px; overflow:auto" align="center">';
        m[m.length] = '  <table cellspacing="0" cellpadding="0">';
        m[m.length] = '    <tr>';
		
		for (var i = 0; i < thumbHTMLs.length; ++i) {
			m[m.length] = '      <td align="center" style="font-size: 0px; line-height: 0px">';
			m[m.length] = '<div style="margin-right: 10px; width: 80px">';			
			m[m.length] = thumbHTMLs[i].replace(/>$/, " width=\"80\" height=\"80\" onclick=\"$('collactive_thumb_radio_"+i+"').click()\">");
			m[m.length] = '<div style="margin-top: 10px">';
			m[m.length] = '			<input id="collactive_thumb_radio_'+i+'"';
			if (i == 0) {
				m[m.length] = 'checked="checked"';
			}
			m[m.length] = 'type="radio" value="1" name="collactive_thumb"/>';
			m[m.length] = '</div>';
			m[m.length] = '</div>';
			m[m.length] = '      </td>';
		}
		
        m[m.length] = '    </tr>';
        m[m.length] = '  </table>';
        m[m.length] = '</div>';
        this.displayContent('Choose thumbnail', 'Choose the thumbnail that best represents your submission.',
                            this._siteLogo, m.join("\n"),
                            [["Next", Collactive.bind(this, function() {
                                Collactive.CSAUtils.notifyOperation("assist_choose_thumb");
								for (var i = 0; i < thumbHTMLs.length; ++i) {
									if (Collactive.DomUtils.gEBI('collactive_thumb_radio_'+i).checked) {
										cb.onThumbChosen(i);
										return;
									}
								}
                              })]],
                            cb.onThumbCanceled ? [["Cancel", Collactive.bind(this, function() {
                                    if (confirm("Are you sure you'd like to close Collactive Web Assistant?")) {
                                    this.hideUI();
                                    Collactive.CSAUtils.notifyOperation("assist_no_thumb");
                                    cb.onThumbCanceled();
                                }
                                })]] : null
                            );
    };



    this.displayEmailErrorPrompt = function(type, emailAddress, cb) {
        var fieldsMetadata = {
            emailAddress: {
                prompt: "Email address",
                description: "Please enter a valid address as it may be confirmed",
                validate: function(value) {
                    if (!value.match(/^[a-z0-9\-\.\_\+]{1,}@[a-z0-9\-\.]+\.[a-z]{2,4}$/i)) {
                        return false;
                    }
                    if (value == emailAddress) {
                        return false;
                    }
                    return true;
                },
                errorString: "Please enter a new, valid email address"
            }
        };

        var h = [];
        if (type == "taken") {
            h[h.length] = this._siteName + " already has an account with the email address";
        } else if (type == "error") {
            h[h.length] = this._siteName + " could not accept your email address";
        }

        h[h.length] = " <b>" + emailAddress + "</b>.";
        h[h.length] = '<div style="margin-top: 10px; margin-bottom: 20px">';
        h[h.length] = 'Please provide another email address to use.';
        h[h.length] = '</div>';

        var e = [];
        e[e.length] = '<div style="margin-top: 20px">';
        e[e.length] = '<a href="#" onclick="addExistingAccount(); return false;">';
        if (type == "taken") {
            e[e.length] = 'I remember my existing ' + this._siteName + ' account and would like to use it';
        } else if (type == "error") {
            e[e.length] = 'I would like to use an existing ' + this._siteName + ' account';
        }
        e[e.length] = '</a>';
        e[e.length] = '</div>';

        window.addExistingAccount = Collactive.bind(this, function() {
            Collactive.CSAUtils.notifyOperation("assist_newemail_existing");
            cb.onUseExisting();
        });

        this._wizard.displayForm('Email address not accepted', h.join(""),
                                 this._siteLogo, ["emailAddress"], fieldsMetadata,
                                 Collactive.bind(this, function() {
                                     Collactive.CSAUtils.notifyOperation("assist_newemail_given");
                                     cb.onNewEmail(Collactive.DomUtils.gEBI("collactive_wizard_form_emailAddress").value);
                                 }),
                                 Collactive.bind(this, function() {
                                    if (confirm("Are you sure you'd like to close Collactive Web Assistant?")) {
                                        this.hideUI();
                                        Collactive.CSAUtils.notifyOperation("assist_newemail_cancel");
                                        cb.onCancel();
                                    }
                                 }),
                                 e.join("")
                                 );
    };

    this.displayErrorMessage = function(msg) {
        msg = "Collactive Web Assistant detected an error.";

        Collactive.CSAUtils.notifyOperation("assist_error");
        this._wizard.displayContent("Oops! We seem to have a problem.", msg, null,
                                    "We apologize for the inconvenience. The error has been reported to the"
                                    + " Collactive team and will be examined."
                                    + "<div style='margin-top: 20px; font-weight: bold'>Would you like to try again?</div>",
                                    [["Yes, try again", Collactive.bind(this, function() {
                                        Collactive.CSAUtils.notifyOperation("assist_error_retry");
                                        document.location.reload();
                                      })]],
                                    [["No thanks", Collactive.bind(this, function() {
                                        this.hideUI();
                                        Collactive.CSAUtils.notifyOperation("assist_error_close");
                                    })]]);
    };

    this.displayFreeContent = function(contentHTML, nextButtons, cancelButtons) {
        this._wizard.displayFreeContent(contentHTML, nextButtons, cancelButtons);
    };

    this.displayContent = function(subtitle, description, logo, contentHTML, nextButtons, cancelButtons) {
        this._wizard.displayContent(subtitle, description, logo, contentHTML, nextButtons, cancelButtons);
    };

    // Hide wizard
    this.hideUI = function() {
        this._wizard.hide();
    };

	this.startAnimationMode = function(controlCallbacks) {
		this._wizard.startAnimationMode(controlCallbacks);
	};

	this.stopAnimationMode = function(controlCallbacks) {
		this._wizard.stopAnimationMode();
	};

    // Display a "registering to website" message
    this.displayRegisteringMessage = function() {
        this.displaySiteProgressMessage('Registering to <font color="black">' + this._siteName + '</font>');
    };

    this.displayPecentageProgress = function(title, percent_done) {
		this._wizard.displayProgress(title, null, null, percent_done);		
	}


    // Display a "Logging in" message
    this.displayLoggingInMessage = function() {
        this.displaySiteProgressMessage('Logging in to <font color="black">' + this._siteName + '</font>');
    };

    this.displayLoadingMessage = function() {
        this.displaySiteProgressMessage('<font color="black">' + this._siteName + '</font> is loading');
    };

    this.displayPerformingActionMessage = function() {
        this.displaySiteProgressMessage('Performing your action on <font color="black">' + this._siteName + '</font>');
    };

    this.displaySiteProgressMessage = function(subtitle, description) {
        this._wizard.displayProgress(subtitle, description, this._siteLogo)
    };

    this.displayProgressMessage = function(subtitle, description, logo) {
        this._wizard.displayProgress(subtitle, description, logo)
    };

    this.addFirstStep = function(stepPair) {
       this._wizard.addFirstStep(stepPair);
    };

    this.addStepAfter = function(stepPair, existingStepName) {
       this._wizard.addStepAfter(stepPair, existingStepName);
    };

    this.displayStep = function (stepName) {
        this._wizard.gotoStepByName(stepName);
    };

    this.refreshStepDisplay = function() {
        this._wizard.refreshStepDisplay();
    };

	this.getImageUrl = function(name) {
		return "http://" + document.location.host + "/images/assistant/" + name;
	};

    this.setHideMode = function(newMode) {
        this._wizard.setHideMode(newMode);
    };

    this.resetHideMode = function() {
        this._wizard.resetHideMode();
    };

	this.hideArticle = function() {
	   var article = document.getElementById('article');
	   if (article != null) {
	       article.style.display = 'none';
	   }
	};

	this.showArticle = function() {
	   var article = document.getElementById('article');
	   if (article != null) {
	       article.style.display = 'block';
	   }
	};

	this.getSiteName = function() {
	   return this._siteName;
	};

	this.addDisplayListener = function(listener) {
	   return this._wizard.addDisplayListener(listener);
	};

    if (this._siteLogo) {
        this._wizard.addPreloadImages([this._siteLogo]);
    }

	return this;
};
