/*
 * Copyright (C) 2009 WorkSmart Labs, Inc.
 */

/**
 * 
 *
 * @author Vera Kern <vera@worksmartlabs.com>
 */

var LINK_TEXT = 'Hello, I would like to share a track with you: ' +
                'http://www.worksmartlabs.com/cardiotrainer/' +
                'tracks.php?trackId=';
                
var FROM_EMAIL_ADRESS_DEFAULT = 'your@email.com';

ShareTrackDialog.ShareTrackStatus = { sent: 1, invalidAdress: 2, failed: 3 };

/**
 * Creates a new ShareTrack object.
 * @param container DOMElement container where to put the form. 
 */
 
function ShareTrackDialog(container) {
    this.container_ = container;
    this.shareTrackDialogVisible_ = false;
    this.currentId_ = null;
    
    var showShareTrack = el('share_track_dialog');
    setClickHandler(showShareTrack, this, this.toggleShareTrackDialog);
    
    var closeShareTrack = el('close_share_track');
    setClickHandler(closeShareTrack, this, this.toggleShareTrackDialog);
    
    var sendSharedTrack = el('send_track');
    setClickHandler(sendSharedTrack, this, this.sendTrack);

    this.fromEmailTextView_ = new TextViewWithDefaultText(el('emailFrom'), 
                                                         FROM_EMAIL_ADRESS_DEFAULT);
    this.fromEmailTextView_.setDefault();
    
    var previewSharedTrack = el('preview_mail');
    setClickHandler(previewSharedTrack, this, this.previewTrack);
} 

/**
 * This function shows/hides the shareTrackDialog div.
 *
 */
ShareTrackDialog.prototype.toggleShareTrackDialog = function() {
    if (this.shareTrackDialogVisible_) {
        displayNone(this.container_);
        this.shareTrackDialogVisible_ = false;
    } else {
        displayBlock(this.container_);
        this.shareTrackDialogVisible_ = true;
        el('emailTo').focus();
    }
}

/**
 * This function set text for the shared track mail.
 *
 * @param DOM element container
 */
ShareTrackDialog.prototype.setValues = function(currentId) {
    this.currentId_ = currentId;
    el('feedback').firstChild.nodeValue = '\u00A0';
}

/**
 * This function sends the mail to the specified emailaddresses
 */

ShareTrackDialog.prototype.sendTrack = function() {
    
    var send_button = el('send_track');
    send_button.blur();
    send_button.firstChild.nodeValue = 'Sending...'; 
    if (this.checkEmailAdresses_()) {
        var ajaxRequest = createAjaxRequestObject();
        var url = this.buildUrl(false);
        ajaxRequest.open("GET", url)
        ajaxRequest.send(null);                         
        // When the state changes to "complete" (4)...
        me = this;
        ajaxRequest.onreadystatechange = function(){
            if (ajaxRequest.readyState == 4){
                // The responseText is 1 if the mail was sent successfully
                me.setFeedback_(ajaxRequest.responseText);
            }
        }
    } else {
        this.setFeedback_(2);
    }        
}

/**
 * This function opens a popupwindow and displays
 * a preview of the mail.
 *
 */
ShareTrackDialog.prototype.previewTrack = function() {
    var url = this.buildUrl(true);
    var popup = window.open(url, 'preview', 'height=520, width=650, location=0');
    return false;
}

/**
 * This function builds the url for the preview or to send an email.
 *
 * @param bool isPreview
 */
ShareTrackDialog.prototype.buildUrl = function(isPreview) {
    var to = el('emailTo').value;
    var msg = escape(el('message').value);
    
    var url = 'sharing/send_track.php?trackId=' + this.currentId_ + 
                                    '&to=' + to + '&msg=' + msg;
    if (isPreview) {
        url = url + '&preview=1';
    } else {
        var from = this.trim_(el('emailFrom').value);
        url = url + '&from=' + from;
    }
    return url;
}

/**
 * This function sets the feedback color and content depending on the status.
 *
 * $param int status
 */
ShareTrackDialog.prototype.setFeedback_ = function (status) {
    if (status == ShareTrackDialog.ShareTrackStatus.sent) {
        el('feedback').className = 'text green';
        el('feedback').firstChild.nodeValue = 'Email sent';
    } else {
        el('feedback').className = 'text red';
        if (status == ShareTrackDialog.ShareTrackStatus.invalidAdress) {
            el('feedback').firstChild.nodeValue = 'E-mail address is invalid';
        } else if (status == ShareTrackDialog.ShareTrackStatus.failed) {
            el('feedback').firstChild.nodeValue = 'Email could not be sent';    
        } else {
            return;    
        }
    }
    el('send_track').firstChild.nodeValue = 'Send'; 
}

/**
 * This function checks if all provided emailadresses are valid.
 *
 */
ShareTrackDialog.prototype.checkEmailAdresses_ = function() {
    var to = el('emailTo').value;
    var from = this.trim_(el('emailFrom').value);
    
    var isValid = true;
    var toArray = to.split(",");
        for (i = 0; i < toArray.length; i++) {
            var email = this.trim_(toArray[i]);
            isValid = isValid && this.isEmailAdressValid_(email);
        }    
    isValid = isValid && this.isEmailAdressValid_(from);
    return isValid;
}

/**
 * This function checks if the provided e-mail address is valid
 *
 * @param string email
 */
ShareTrackDialog.prototype.isEmailAdressValid_ = function(email) {
    var pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (pattern.test(email) && (email != 'your@email.com')) {
        return true;
    } else {
        return false;
    }
}

/**
 * This function removes whitespaces from a string.
 *
 * @param string string
 */
ShareTrackDialog.prototype.trim_ = function(string) {
    return string.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
