function submitSend() {
    var message = $("#message").val();
    var date = $("input#deliv-date").val();
    var to  = $("#recip-email").getReceivers();
    var num = 0;
    var send_type = $("#send_type").val();
    var is_anonymous = $("#is_anonymous").val();
    var allowed_num_for_anonymous = $("#allowed_num_for_anonymous").val();

    if(!Boolean(typeof to!='undefined' && to) || to.length<=0 || (typeof to == "string")){
        if(typeof to == "string") showMessage(to, "Alert");
        else showMessage("You must specify recipient(s)", "Alert");
        return false;
    }

    num = to.length;

    if(num > 50){
        showMessage("Only 50 recipients allowed at a time.", "Alert");
        return false;
    }

    if (is_anonymous == 1) {
        var sender_name  = $("#senders_name").val();
        var sender_email = $("#senders_email").val();
        if (!validateEmail(sender_email)) {
            alert(sender_email);
            showMessage("Error: The address in the \"From\" field is an an unrecognized format.", "Alert");
            return false;
        }

        if (num > allowed_num_for_anonymous) {
            showAnonsendError(2);
            return false;
        } 

        $("input:hidden#sendcard_sender_name").val(sender_name);
        $("input:hidden#sendcard_sender_email").val(sender_email);
    }


    var to_formatted = new Array();
    for(var t in to){
        if(Boolean(typeof to[t].email!='undefined' && to[t].email))
            to_formatted.push(to[t].email);    
    }

    $("input:hidden#sendcard_message").val(message);
    $("input:hidden#sendcard_to").val(to_formatted.join(", "));
    $("input:hidden#sendcard_date").val(date);
    $("input:hidden#sendcard_send_type").val(send_type);

    $("input:hidden#sendcard_subscribe").val( $("#news-opt-in").attr('checked') ? 1 : 0);
    $("input:hidden#sendcard_notify").val( $("#notify").attr('checked') ? 1 : 0);
    $("input:hidden#sendcard_send_copy").val( $("#send-copy").attr('checked') ? 1 : 0);
    $("input:hidden#sendcard_notify_miss").val( $("#notify-three-day").attr('checked') ? 1 : 0);    

	//Convert to Military Time
	var time =  $("#time").val();
	if((time != "Now") && (time != "Midnight") && (time != "Noon")){
        var am = (time.substring(time.length-2)=="am") ? true : false;
        var h = parseInt(time.substring(0,2));
        if(time.length == 6) time = "0"+time;
		if(am){
			if(h == 12) h=0;
		} else {
			if(h < 12) h+= 12;
		}
		if(h < 10) h = "0"+h;
		time = h + time.substring(2,5);
	}
    $("input:hidden#sendcard_when").val(time);

    if (is_anonymous == 1) {

        var form_data = $('form#sendcard_form').serializeArray();

        $.ajax({
                'url': config.base_path + '/card/send',
                'async': false,
                'dataType': 'json',
                'type': 'post',
                'data': form_data,
                'success': function(data) {
                    if (data.status == 'OK') {
                        var hash = data.hash;
                        location.href = "/confirm-send/" + hash;
                    } else {
                        //popup.jqmHide();
                        var errNum = data.errorNum;
                        if (errNum == 3) 
                            showCommonError();
                        else
                            showAnonsendError(errNum);
                    }
                } 

            });
        
        return false;
    }
    $("form#sendcard_form").submit();
}


function showAnonsendError(err) {
    if (err == 1) {
        var popup = $("#popup");
        loadLoginPopup("sendcard_anonymous_login");
        $("h3", popup).html("You must log in to send more cards today");
        $("#popup_before_content").html("Sorry, we have to do this for security reasons.");
    } else {
        var popup = $("#popup");
        loadLoginPopup("sendcard_anonymous_login");
        $("h3", popup).html("You must log in to send a card to that many people");
        $("#popup_before_content").html("Sorry, we have to do this for security reasons.");
    }
}

function showCommonError() {
    showMessage("Some error happens. Please try to force reload your browser and repeat last action.", "Error");
}

function showPreview() {
    $("body").removeClass().addClass("preview-card");
    //$("#send-card-view .sent-email").html(getTo().split(',')[0]);
    var to = $("#recip-email").getReceivers();
    var to_preview = new Array();
    for(var t in to){
        if(Boolean(typeof to[t].name!='undefined' && to[t].name))
            to_preview.push(to[t].name);
        else if(Boolean(typeof to[t].email!='undefined' && to[t].email))
            to_preview.push(to[t].email);
    }

    $("#send-card-view .sent-email").html(to_preview.join(", "));
    $("#preview-message").html(replaceReturn($("#message")[0], "<br />"));
    $("#send-card-view .sendcard-element").hide();
    $("#send-card-view .preview-element").show();
    $("#card-wrapper").removeClass("send-workflow").addClass("view-card-wrp");
    $("#send-card-view .steps-fav span.create").removeClass("on");
    $("#send-card-view .steps-fav span.prv").addClass("on");
    /*
    if(document.body.id == "someusercards"){
        $("#preview-flash").html($("#flash").html());
    }
    */
	
    $.equilize("#content","#right-rail");
    return false;
}

function showEdit() {
    $("body").removeClass().addClass("send-card");
    $("#send-card-view .preview-element").hide();
    $("#send-card-view .sendcard-element").show();
    $("#card-wrapper").removeClass("view-card-wrp").addClass("send-workflow");
    $("#send-card-view .steps-fav span.create").addClass("on");
    $("#send-card-view .steps-fav span.prv").removeClass("on");
    return false;
}

// START LOGIN TAB FBCONNECT
function sendcardLogin() {
    var username = $("#sc_username").val();
    var password = $("#sc_password").val();
    //var makefblink = $(".fbidsec_makelink").val()=="true";
    $.post(config.base_path + "/user/popup_login", {'popup-login-email':username, 'popup-login-password':password} ,function(r){
            var rVal = eval("(" + r + ")");
	    if(rVal.status=="FAIL" && rVal.error=="Already logged in"){
                reloadPage();
            } else if(rVal.status=="FAIL") {
		showMessage("Wrong login/password", 'Alert');
	    } else {
		if (rVal.status == "IMPORT REQUIRED") {
                    showMessage("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>","Please wait while we build your inbox. This will only happen the first time you log in");
                $.ajax({
                    'url': config.base_path + '/user/importaccount',
                    'async': false,
                    'dataType': 'json',
                    'success': function(data) {
                        showMessage("Import Finished.  Thanks!", "Please wait while we build your inbox. This will only happen the first time you log in", function(){ reloadPage(); });
                    }
		});
                } else {
                    reloadPage();
                }
	    }
	});
    return false;
}

function submitCard(form_id, url) {
    var form = document.getElementById("form-" + form_id);
    form.action = url;
    form.submit();
    //$("#form-" + form_id).attr('action', url).submit();
    return false;
}

function favoriteCard(obj, is_social_overlay) {
    var info  = ($(obj).attr('id')).substr(4);
    var delim = info.indexOf('_');
    var card_id   = info.substr(0, delim);
    var card_type = info.substr(delim + 1);
    is_social_overlay =(Boolean(typeof is_social_overlay!='undefined' && is_social_overlay));

    $.get(config.base_path + "/user/favorite", {'card_id':card_id,'card_type':card_type}, function(data, textStatus){
        if(textStatus == 'success') {
           if(data.status == 'OK') {
                if(is_social_overlay){
                    $(obj).removeClass("social-favorite").addClass("social-unfavorite").unbind("click").html("Unfavorite").click(function() { return removeFromFav(this, true)});
                }
                else {
                    //showMessage("Card has been favorited.","Success!");
                    $(obj).removeClass("check").addClass("check_on").unbind("click").html("Remove from Favorites").click(function() { return removeFromFav(this)}).parent().removeClass("add-to-fav").addClass("remove-fav");
                }
           } else {
                if(is_social_overlay){
                    $("#cardthumb_overlay .status-message").html(data.error).slideDown();
                }
                else {
                    showMessage("You must be logged in to save cards to favorites.", "Alert!");
                }
            }
        } else {
            if(is_social_overlay){
               $("#cardthumb_overlay .status-message").html(data.error).slideDown();
            }
            else {
                showMessage("Failed to favorite card. Try again later","Alert!");
            }
        }
   }, 'json');
   return false;
}

function removeFromFav(obj, is_social_overlay) {
    var info  = ($(obj).attr('id')).substr(4);
    var delim = info.indexOf('_');
    var card_id   = info.substr(0, delim);
    var card_type = info.substr(delim + 1);
    is_social_overlay =(Boolean(typeof is_social_overlay!='undefined' && is_social_overlay));


    $.get(config.base_path + "/user/favorite-remove", {'card_id':card_id,'card_type':card_type}, function(data, textStatus){
            if(textStatus == 'success') {
                if(data.status == 'OK') {
                    if(is_social_overlay){
                        $(obj).removeClass("social-unfavorite").addClass("social-favorite").unbind("click").html("Favorite").click(function() { return favoriteCard(this, true)});
                    }
                    else {
                        //showMessage("Card has been removed from favorites.", "Success!");
                        $(obj).removeClass("check_on").addClass("check").unbind("click").html("Add to Favorites").click(function() { return favoriteCard(this)}).parent().removeClass("remove-fav").addClass("add-to-fav");
                    }
                } else {
                    if(is_social_overlay){
                        $("#cardthumb_overlay .status-message").html(data.error).slideDown();
                    }
                    else {
                        showMessage("You must be logged in to remove cards from favorites.","Alert!");
                    }
                }
            } else {
                if(is_social_overlay){
                   $("#cardthumb_overlay .status-message").html("Failed to remove favorite card. Try again later.").slideDown();
                }
                else {
                    showMessage("Failed to remove favorite card. Try again later","Alert!");
                }
            }
        }, 'json');

        return false;
}

function replaceReturn(textarea,replaceWith)
{ 
	var val = escape(textarea.value);
	if(val.indexOf("%0D%0A") > -1) 
   		val=val.replace(/%0D%0A/g,replaceWith);
  	if(val.indexOf("%0A") > -1)
   		val=val.replace(/%0A/g,replaceWith);
  	if(val.indexOf("%0D") > -1)
   		val=val.replace(/%0D/g,replaceWith);

	return unescape(val);
}

function afterAttachReplyCard() {
    $("#popup").jqmHide();
    //$("#redirect_form_submit").click();
}

function showAttachReplyCardPopup() {
    var popup = $("#popup");
    popup.css("position","absolute");
    if($.browser.msie){
        popup.css("top",document.documentElement.scrollTop+25);
    } else {
        popup.css("top",window.pageYOffset+25);
    }
    $(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>")
        popup.removeClass().addClass("register"); 
    $("h3",popup).html("Attach a card");			
    $("div.link-button a.unsubscribe",popup).hide();
    $(".content",popup).load("/static/popup-invites-attach-card.php?attach_callback=window.parent.attachReplyCard", function(){});
    $(".link-button .button",popup).html("Attach &raquo;").unbind("click").click(function(){			
            $.ajax({
                    'url': config.base_path + '/invitations/attach_card',
                     'async': false,
                     'dataType': 'json',
                     'type': 'post',
                     'data':  {'hash': hash, 'key': key, 'message' : $("#popup-invites-message-guest").val()},
                     'success': function(data) {
                     if (data.status == 'OK') {
                          alertPop("Card attached");
                          popup.jqmHide();
                     } else 
                          alertPop("<b>An error occurred:</b> " + data.error);
                     } 
                   });
             });
    $(".link-button .button",popup).show();
    popup.jqmShow();
}

function removeRepliedCard() {
    $("#card_container").html("");
    var original_card_id = $("#original_reply_card_id").val();
    var original_card_type = $("#original_reply_card_type").val();

    $("input:hidden#reply_card_id").val(original_card_id);
    $("input:hidden#reply_card_type").val(original_card_type);
    $("#reply-attach-card").html("Attach a card").unbind("click").click(showAttachReplyCardPopup);
    return false;
}

function attachReplyCard(card_id, invited_id, card_type) {
    $("#reply_card_id").val(card_id);
    $("#reply_card_type").val(card_type);

    $.ajax({
            'url': '/card/get_card_html?card_id=' + card_id + '&card_type=' + card_type,
            'async': false,
            'dataType': 'text',
            'type': 'get',
            'success': function(data) {
                $("#card_container").html(data + "<BR>");
                $("#popup").jqmHide();
                $("#reply-attach-card").html("Remove card").unbind("click").click(removeRepliedCard);
            } 
    });
    return false;
}

function cardReportSpam(hash) {
    var popup = $("#popup");
    popup.css("position","absolute");
    if($.browser.msie){
        popup.css("top",document.documentElement.scrollTop+100);
    } else {
        popup.css("top",window.pageYOffset+100);
    }
    
    $(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>");
    $("h3",popup).html("Report this card as spam?");			
    $("div.link-button a.unsubscribe",popup).hide();
    $(".link-button .need-account",popup).hide();
    $("#popup_cancel").show();
    $(".content",popup).html("<hr><span style='font-size: 14px;'>Please confirm that this card is spam.</span>");


    $(".link-button .button",popup).html("Confirm &raquo;").unbind("click").click(function(){			

    $.ajax({
            'url': "/report-spam?hash=" + hash,
            'async': false,
            'dataType': 'json',
            'type': 'get',
            'success': function(data) {
                $("#popup_cancel").hide();
                popup.jqmHide();
                showMessage("An admin has been notified and will take steps to resolve the issue.", "Admin Alerted!");
            } 
    });

    });
    $(".link-button .button",popup).show();
    popup.jqmShow();

    return false;
}

function submitSendAfterLogin() {
     $("#is_anonymous").val(0);
    submitSend();
}