/*

Copyright 2011, GuerrillaMail.com
Author: Clomode, flashmob@gmail.com

*/

function gm_init() {
    
    gm_lang();
    gm_init_vars();
    
    messages = new mail_messages();
    
    if (typeof $('.editable').inlineEdit !== 'undefined') {
    $('.editable').inlineEdit({
    	hover: 'ui-state-hover',
        buttonText: 'Add',
    	placeholder: gm_lang.label.inline_placeholder,
    	buttons: '<button class="save">'+gm_lang.label.inline_button_set+'</button> <button class="cancel">'+gm_lang.label.inline_button_cancel+'</button>',
        save: 
        function(e, data) {
            if (this.id=='email') {
                set_email(data.value);
            }
        }
    });
    
    }
    
    
    
    $("#forget_button").click(function(event) {
        event.preventDefault();
        status_alert(gm_lang.label.status_alert_forgetme);
        
        $.ajax({
            url: 'http://'+gm_init_vars.ajax_url+'?f=forget_me',
            dataType: 'json',    
            type: 'GET',
            tryCount : 0,
            retryLimit : 3,
            cache: false,
            error: 
                function(xhr, textStatus, errorThrown) { 
                    if (textStatus == 'timeout') {
                        this.tryCount++;
                            if (this.tryCount <= this.retryLimit) {
                                $.ajax(this); // try again
                                return;
                            }
                        }
                        
                        if (xhr.status == 500) {
                            // problem with server
                        } else {
                            // connection probs?
                        }
                        
           
                },
            success: 
       	        function(result) {
                	   
                    status_alert(gm_lang.label.forgetten_alert);
                    
                    expired_state();
                	   
                    
               	}
        });
        
    });

    $("#extend_button").click(function(event) {
        
        event.preventDefault();
        
        $.ajax({
            url: 'http://'+gm_init_vars.ajax_url+'?f=extend',
            dataType: 'json',
                
            type: 'GET',
            tryCount : 0,
            retryLimit : 3,
            cache: false,
            error: 
                function(xhr, textStatus, errorThrown) { 
                    if (textStatus == 'timeout') {
                        this.tryCount++;
                            if (this.tryCount <= this.retryLimit) {
                                $.ajax(this); // try again
                                return;
                            }
                        }
                        
                        if (xhr.status == 500) {
                            // problem with server
                        } else {
                            // connection probs?
                        }
                        
           
                },
            success: 
       	        function(result) {
                	   
                    if (result.email_timestamp > mail_messages.email_timestamp) {
                        status_alert(gm_lang.label.time_extended);
                    } else {
                        status_alert(gm_lang.label.time_extend_error);
                    }
                    mail_messages.email_timestamp = result.email_timestamp;
                	   
                    
               	}
        });
        
    });
  
    set_click_event('.mail_row');
    setInterval(gm_tick, 1000); // tick every second
    
    
    
    $("#copy_to_clip").each(function(i) {
        document.clip.addEventListener('complete', function(client, text) {
            status_alert(gm_lang.label.copied_to_clip + "<b>" + text+'</b>');
        });
        document.clip.addEventListener( 'onMouseOver', function() {
            $("#copy_to_clip").addClass('hovered')
        });
        
        document.clip.addEventListener( 'onMouseOut', function() { 
            $("#copy_to_clip").removeClass('hovered')
        });
        
        document.clip.addEventListener( 'onMouseDown', function() { 
            $("#copy_to_clip").addClass('activated')
        });
        
        document.clip.addEventListener( 'onMouseUp', function() { 
            $("#copy_to_clip").removeClass('activated')
        });
     
         document.clip.setText($("#email").text()+'@'+gm_init_vars.display_host);
         document.clip.glue($(this).attr("id"));
        
    });
    
    $("#copy_to_clip").mouseover(function() {
        document.clip.reposition(this);
    });
    
    $("#del_button").click ( function (event) {
        event.preventDefault();
        
        // build the list of emails to be deleted
        var del_list = [];
        $(".mail_row :checked").each(function() { 
            del_list.push($(this).val());
        } );
        // now send the request to base
        status_alert(gm_lang.label.delete_sent);
        delete_mail(del_list);
        
    });
    
    /// setup tabs
    
    $.address.init(function(event) {
 
        // Initializes the plugin
        $(".nav_item a").address(); // tab links  
        
        }).change(function(event) {
  
                var tab_param = $.address.parameter("t");
                
                if (typeof tab_param === 'undefined') {
                    tab_param = 'inbox'; // open with the inbox tab by default
                }
              
                // .tab_content show / hide the appropriate tab
                
                $(".tab_content").each( function () {

                    var t_selector = "#nav-item-"+$(this).attr('id');
                    if ($(this).attr('id') === tab_param) {
                        $(t_selector).addClass('current_nav_item');
                        $(this).addClass('active_tab');
                        $.address.title($(this).attr('data-title'));
                        $(this).removeClass('hidden_tab');
                      //  $.address.update()
                        
                    } else {
                        $(t_selector).removeClass('current_nav_item');
                        $(this).removeClass('active_tab');
                        $(this).addClass('hidden_tab');
                    }
             
                });
            });
            
            
            // hover the menu
            $(".nav_item").hover( 
                function() {
                    $(this).addClass('nav_hover');
                    $(this).children("a").addClass('nav_hover_a');
                    
                    $(this).removeClass('nav_not_active');
                    $(this).children("a").removeClass('nav_not_active_a');
                },
                function() {
                    $(this).removeClass('nav_hover');
                    $(this).children("a").removeClass('nav_hover_a');
                    
                    $(this).addClass('nav_not_active');
                    $(this).children("a").addClass('nav_not_active_a');
                }
            );
    
    
}

////////////////////////////////////////////////////////////////////////

/*
Data structure for the intrefce.
*/
function mail_messages() {

    
    
    mail_messages.limit = gm_init_vars.limit;
	mail_messages.res = gm_init_vars.result;
    mail_messages.total_count = mail_messages.res.count;
    mail_messages.email = gm_init_vars.email_addr;
    mail_messages.email_timestamp = gm_init_vars.email_timestamp;
    mail_messages.s_active = gm_init_vars.s_active;
    mail_messages.s_date = gm_init_vars.s_date;
    mail_messages.s_time = gm_init_vars.s_time;
    mail_messages.s_time_expires = gm_init_vars.s_time_expires;
    
    mail_messages.reset = function() {
        mail_messages.total_count = 0;
        mail_messages.email = '';
        mail_messages.email_timestamp = 0;
        mail_messages.s_active = 'N';
        mail_messages.s_date = '';
        mail_messages.s_time = 0;
        mail_messages.s_time_expires = 0;
    }
	this.getList = function() {
	   
        if ( typeof mail_messages.res.list == 'undefined' ) {
            mail_messages.res.list = [];
        }
        return mail_messages.res.list;
        
	};
    
    this.getStats = function() {
        
        return mail_messages.res.stats;
        
    }
    
    this.renderList = function() {
        
        $(".mail_row").each( function(i) {
            $(this).remove();
        });
        
        var row_html = '';
        var list = this.getList();
    
        for (var i=0; i <  list.length; i++) { 
            row_html = get_row_html(list[i]);
            $('#email_list').append(row_html);     
        }
        set_click_event('.mail_row'); 
        no_emails_row_check()
        
        
    }
    
    this.loadList = function(offset) { // not async, will block until the list is loaded
        
        // re-load the list for the current set email.
        
        $.ajax({
        url: 'http://'+gm_init_vars.ajax_url+'?f=get_email_list',
        dataType: 'json',
        data: {offset: offset},
        type: 'GET',
        async: false,
        tryCount : 0,
        retryLimit : 3,
        cache: false,
        error: 
        	function(xhr, textStatus, errorThrown) { 
                if (textStatus == 'timeout') {
                    this.tryCount++;
                     if (this.tryCount <= this.retryLimit) {
                        $.ajax(this); // try again
                        return;
                     }
                }
                
                if (xhr.status == 500) {
                    // problem with server
                } else {
                    // connection probs?
                }
                
                status_alert(gm_lang.label.reload_error);
           
        	},
        success: 
        	function(result) {
        	   
                if ((result == null ) || ( typeof result.list == 'undefined' )) {                   
                    return false;
                } else {
                    mail_messages.res = result;
                    mail_messages.total_count = mail_messages.res.count;
                }
           
        	}
        });
        
        
    }

}


////////////////////////////////////////////////////////////////////////

function get_row_html(item, is_hidden) {
    var unread_class = '';
    if (item.mail_read != 1) {
        unread_class = ' email_unread';
    } else {
        unread_class = '';
    }
    var hidden_style;
    
    if (is_hidden) {
        hidden_style = 'display:none;'
    }
    
   
    var row_html = gm_init_vars.row_template;
    row_html = row_html.replace(/%MAIL_ID%/g, item.mail_id);
    row_html = row_html.replace(/%HIDDEN_STYLE%/g, hidden_style);
    row_html = row_html.replace(/%UNREAD_CLASS%/g, unread_class);
    row_html = row_html.replace(/%MAIL_FROM%/g, item.mail_from);
    row_html = row_html.replace(/%MAIL_DATE%/g, item.mail_date);
    row_html = row_html.replace(/%MAIL_SUBJECT%/g, item.mail_subject);
    row_html = row_html.replace(/%MAIL_EXCERPT%/g, item.mail_excerpt);
     
    return row_html;
    
    
}

////////////////////////////////////////////////////////////////////////
// Change the email address
function change_email(email_addr, email_timestamp, s_active, s_date, s_time, s_time_expires ) {
    change_email.status = 'WORKING';
    mail_messages.email = email_addr;
    mail_messages.email_timestamp = email_timestamp;
    
    // subscriber data
    mail_messages.s_active = s_active;
    mail_messages.s_date = s_date;
    mail_messages.s_time = s_time;
    mail_messages.s_time_expires = s_time_expires;
    
    $("#email").text(email_addr.split(/@/).shift());
    document.clip.setText($("#email").text()+'@'+gm_init_vars.display_host);
                
    // remove the list and load in the new emails.

    messages.loadList(0);
    messages.renderList();
    
    // does this email have a subscription?
    
    if (mail_messages.s_active == 'Y') {
        unlock_extras();
        
    } else {
        lock_extras();
    }
    
    change_email.status='READY'
    
    
   
}

////////////////////////////////////////////////////////////////////////

function unlock_extras() {
    status_alert(gm_lang.label.sub_unlocked);
    
    // swap the iframe to the control panel :P
    $("#extras_iframe").attr('src', 'http://www.guerrillamail.com/guerrillamail/forwarding.php?from_ajax=1');
    
  
}

function lock_extras() {
    $("#extras_iframe").attr('src', 'http://www.guerrillamail.com/guerrillamail/order.php?from_ajax=1&forget=1&lang='+gm_init_vars.lang);
}
////////////////////////////////////////////////////////////////////////
function update_stats(stats) {
    
    // update stats
                            
    var str = gm_init_vars.stats_template;
    
    if (update_stats.received_emails) {
		var temp = stats.received_emails.replace(/,/g, ''); // thousands separated using ',' 
		var diff = parseInt(temp) - parseInt(update_stats.received_emails);
		var diff = ' <span class="increase">(+'+diff+')</span>';
	} else {
		var diff = '';
	}
    update_stats.received_emails = stats.received_emails.replace(/,/g, '');
    
    str = str.replace('%RECEIVED_EMAILS%', stats.received_emails);
    str = str.replace('%DIFF%', diff);
    str = str.replace('%SEQUENCE_MAIL%', stats.sequence_mail);
    str = str.replace('%TOTAL%', stats.total);
    str = str.replace('%TOTAL_PER_HOUR%', stats.total_per_hour);
    
    $("#stats").html(str);
                        
}

////////////////////////////////////////////////////////////////////////
// This function ticks every second to update the interface and check
// the emails every 10 seconds. ()It will not check the email if the function
// is still busy from a previous tick)

function gm_tick() {

    
    var next_update_str;

    if ( typeof gm_tick.status == 'undefined' ) {
        gm_tick.status = 'READY';
        
    } else if(gm_tick.status=='WORKING') {
        return; // ensures that ticks are synchronized
    } else if(gm_tick.status!='PAUSED') {
        
        var time = Math.round(new Date().getTime() / 1000);
        var elapsed = time - mail_messages.email_timestamp;
        var remaining = (60*60)-elapsed;
        
        if (remaining > 0) {
            var days = Math.floor ( remaining/86400 ); //calculate the days
            remaining = remaining - (days*86400); // subtract the days
        
            var hours = Math.floor ( remaining/3600 ); // calculate the hours
            remaining = remaining - (hours*3600); // subtract the hours
        
            var mins = Math.floor ( remaining/60 ); // calculate the minutes
            remaining = remaining - (mins*60); // subtract the mins
        
            var secs = remaining; // what's left is the seconds;
            
            var expires = '';
            if (!isNaN(days) && (days > 0)) {
                expires = days+gm_lang.label.days+' ';
            }
            if (!isNaN(hours) && (hours > 0)) {
                expires = expires+hours+gm_lang.label.hrs+' ';
            }
            
            if (!isNaN(mins) && (mins > 0)) {
                expires = expires+mins+gm_lang.label.min+' ';
            }
            
            if (!isNaN(secs) && (secs > 0)) {
                expires = expires+secs+gm_lang.label.sec+' ';
            }
            
            $("#expires").removeClass('expired')
        
        } else {
            
            expires = gm_lang.label.email_expired;
            expired_state();
        }
        
        $("#expires").html(expires);
        
    }

    if ( typeof gm_tick.count == 'undefined' ) {
        gm_tick.count = 0;
    }

	if (gm_tick.count==0) {
        $("#tick").html('<img src="/checking-mail.gif" align="top" border="0" alt="'+gm_lang.label.hold_on+'">'+gm_lang.label.checking);
			
        seq = $(".mail_row:first").attr('data-seq'); // get the sequence (mail_id)
            
        if (typeof seq == 'undefined') {         
            seq = 0;
        }
           
        gm_tick.status = 'WORKING';
           
        $.ajax({
            url: 'http://'+gm_init_vars.ajax_url+'?f=check_email',
            dataType: 'json',
            data: {seq : seq},
            type: 'GET',
            tryCount : 0,
            retryLimit : 3,
            cache: false,
            error: 
              	function(xhr, textStatus, errorThrown) { 
                    if (textStatus == 'timeout') {
                        this.tryCount++;
                        if (this.tryCount <= this.retryLimit) {
                            $.ajax(this); // try again
                            return;
                        }
                    }
                        
                    if (xhr.status == 500) {
                        // problem with server
                    } else {
                        // connection probs?
                    }
                        
                    gm_tick.status = 'READY'
                        
           
                },
                success: 
                function(result) {
                    $("#tick").text( gm_lang.label.done);
 
                        
                    if (result.stats) {
                        update_stats(result.stats);
                    }
                    if (result.email) {
                        // the server can change the email and time stamp at any time
                        if ((mail_messages.email!=result.email)) {
                            // it looks like the email was changed
                            // (possibly in another borwser window)
                            change_email(result.email,  result.ts, result.s_active, result.s_date, result.s_time, result.s_time_expires )
                            gm_tick.status = 'READY'
                            return;
                               
                        }
                            
                                                    
                    }                                                                        
        
                    if ((result == null ) || ( typeof result.list == 'undefined' )) {

                        gm_tick.status = 'READY'
                        return false;
                    } else {
                        var mail_list = result.list;
                    }
                    if ((mail_list) && (change_email.status!=='WORKING')) { // if change_email.status is WORKING then browser is in the process of setting an email?
                        

                        if (mail_list.length > 0) {
                            
                            status_alert(gm_lang.label.new_mail.replace('%length%', mail_list.length));
                        }
                        
                        var row_html = '';
                        for (var i=0; i <  mail_list.length; i++) {
                            row_html = row_html + get_row_html(mail_list[i], true);
                        }
                        $('#email_list').prepend(row_html); // add the new rows
                        
                        no_emails_row_check(); // remove the 'there are no emails' message, if any
                       
                        // set the on-click event for the row
                        var selector_q = ".mail_row:lt("+mail_list.length+")";
                        set_click_event(selector_q);
                        
                        $(selector_q).fadeIn('3000');
                        
                        // remove the oldest rows
                        
                        
                        var row_count = $(".mail_row").length;
                        if ($(".mail_row").length > mail_messages.limit) {
                            // chop the extra rows off the list (:gt uses 0 based index, so subtract 1)
                            $(".mail_row:gt("+(mail_messages.limit-1)+")").hide(1000, 
                                function() {
                                    $(this).remove();
                              
                                });
                                    
                            }

                    }
                        
                        
                    gm_tick.status = 'READY'
                }
        });
        
        gm_tick.count = 10;
			
    } else {
        if (gm_tick.count>0) {
            next_update_str = gm_lang.label.next_update.replace('%count%', gm_tick.count);
            $("#tick").text(next_update_str);
        }
    }
    if (gm_tick.status=='PAUSED') {
        
        $("#tick").text(gm_lang.label.paused);
        
    } else {
 
        gm_tick.count--;
        
    }

}

////////////////////////////////////////////////////////////////////////

// put the interface in an expired state
function expired_state() {
    
    $("#expires").addClass('expired');
    
    // we remove all the emails and place the email in edit mode.

    $(".mail_row").each( function(i) {
        $(this).remove();
    }); 
    
   
    no_emails_row_check();
    
    mail_messages.reset();
    
    lock_extras();
    
    $("#email").text('');
    if (typeof document.clip !=='undefined') {
        document.clip.setText('');
    }    
    
    $(".editable").focus();
    $(".editable").click();   
    
    gm_tick.status = 'PAUSED'; 
    
    
}

////////////////////////////////////////////////////////////////////////
// Return the interface back to the index view state
function back_to_inbox() {
    
    $('#display_email').hide();
    $('#email_table').show();
    window.location.hash = "inbox";
    
}



///////////////////////////////////////////////////////////////

function status_alert(str) {
    
    if (typeof status_alert.count == 'undefined') {
        status_alert.count = 0;
        status_alert.selectors = []; // a stack
    }
    
    
    var toppos  = 0; //$(window).scrollTop();
    
    var sid = "status_alert_"+status_alert.count;
    var sid_sel = '#'+sid;
    status_alert.count++;
    
   var toppx = 30 * $(".status_alert").length;
    
    $('body').append('<div style="top: '+toppx+'px !important;" id="'+sid+'" class="status_alert shadow" >'+str+'</div>');
    
    
    // push the id on the stack, it will be used as a selector for removal
    status_alert.selectors.push(sid_sel);
    
    //re-arrange
     $(".status_alert").each(function (i) {     
        var new_top = (i *30)+toppos;
        $(this).attr('style', 'top: '+new_top+'px !important'); 
     });
           
    $(sid_sel).fadeIn(1000).delay(3000).fadeOut(1000, function() {
        $(status_alert.selectors.shift()).remove(); // filo
        //re-arrange
        $(".status_alert").each(function (i) {     
            var new_top = (i *30)+toppos;
            $(this).attr('style', 'top: '+new_top+'px !important'); 
        });
    });

    
    
}
////////////////////////////////////////////////////////////////////////
function delete_mail(email_ids) {
    var http_req;
    
    if (email_ids.length == 0) return false;
    
    delete_mail.http_req = $.ajax({
    	url: 'http://'+gm_init_vars.ajax_url+'?f=del_email',
    	dataType: 'json',
    	data: {email_ids : email_ids},
    	type: 'POST',
        timeout: '5000',
    	cache: false,
        tryCount: 0,
        retryLimit: 3,
    	error: 
            function(xhr, textStatus, errorThrown) { 
                if (textStatus == 'timeout') {
                    this.tryCount++;
                    if (this.tryCount <= this.retryLimit) {
                        $.ajax(this); // try again
                        return;
                    }
                }
                        
                if (xhr.status == 500) {
                    // problem with server
                } else {
                    // connection probs?
                } 
                status_alert(gm_lang.label.delete_error);
                
                
    		},
    	success: 
            function(result) {
                    
                for (var i=0; i <  result.length; i++) {
                    $("#mr_"+result[i]).hide(100, function() { 
                        $(this).remove();
                       
                    });
                }
                
                var last_seq = $(".mail_row:last").attr('data-seq');
                if (last_seq) {
                    fill_older_list(last_seq, result.length);
                }
                no_emails_row_check()
                
                
                
                
                
            }
    	});
    
    
}
////////////////////////////////////////////////////////////////////////
// check to see if there are any emails in the list, if there are none then append a 'no emails row'
// otherwise remove the 'no emails row' if it exists
function no_emails_row_check() {
    
    var template = gm_init.no_emails_template;
    
    if ($(".mail_row").size()>0) {
        // remove it
        $(".no_emails").remove();             
    } else {
        if ($(".no_emails").size()==0) {
            // add it.
            $('#email_list').append(template);
            
            if (mail_messages.s_active==='Y') {
                $('.no_emails td').html($('.no_emails td').html()+gm_lang.label.forward_note);
            }
            
        }
    }
    
}
////////////////////////////////////////////////////////////////////////

// After deleting some emails, we can add some to the bottom of the list
function fill_older_list(seq, limit) {
    
   
    
    $.ajax({
    	url: 'http://'+gm_init_vars.ajax_url+'?f=get_older_list',
    	dataType: 'json',
    	data: {seq : seq, limit: limit},
    	type: 'GET',
        timeout: '5000',
    	cache: false,
        tryCount: 0,
        retryLimit: 3,
    	error: 
            function(xhr, textStatus, errorThrown) { 
                if (textStatus == 'timeout') {
                    this.tryCount++;
                    if (this.tryCount <= this.retryLimit) {
                        $.ajax(this); // try again
                        return;
                    }
                }
                        
                if (xhr.status == 500) {
                    // problem with server
                } else {
                    // connection probs?
                } 
                status_alert(gm_lang.label.fetch_older_error);
                
                gm_tick.status = saved_gm_tick_status;
               
                
    		},
    	success: 
    		function(result) {
                if ((result == null ) || ( typeof result.list == 'undefined' )) {
                        return false;
                } else {
                    var mail_list = result.list;  
                }
              
                
             
                // now fill the empty space
                var row_html = '';
                for (var i=0; i <  mail_list.length; i++) {
                    row_html = row_html + get_row_html(mail_list[i], true);
                 
                }
                $('#email_list').append(row_html);
                
                for (var i=0; i <  mail_list.length; i++) {
                    var selector_q = "#mr_"+mail_list[i].mail_id;
   
                    set_click_event(selector_q);
                    $(selector_q).fadeIn('1000');
                }
               
                                          
               
               
    		}
    	});
    
}
////////////////////////////////////////////////////////////////////////
// This is what happens when we click on an email in the list
// In this case we fetch and display the email.

function set_click_event(selector_q) {
    
    var http_req;
    
    $(selector_q).addClass('pointer'); // this will render a pointer when the mouse hovers over the row
    
    $(selector_q+" a").addClass('masked_links');
    
    
    $(selector_q).click(function (event) {
        
        // what happens when a mail row is clicked?
        
        var clicked_row_id = '#'+this.id;
    
 
        if ((event.target.tagName == 'INPUT') || (event.target.className == 'td1')) {
            // ignore clicks on the checkbox or first column
            return;
        }
        event.preventDefault();
        
        $(clicked_row_id).removeClass('email_unread');
    
        $('#email_table').hide();
        $('#display_email').html('<div id="loading_email"><img alt="'+gm_lang.label.loading+'" src="/load_email.gif"></div>');
        $('#display_email').show();
        if (set_click_event.http_req) {
            set_click_event.http_req.abort(); // cancel any previous click
        }
        set_click_event.http_req = $.ajax({
            url: 'http://'+gm_init_vars.ajax_url+'?f=fetch_email',
            dataType: 'json',
            data: {email_id : this.id},
            type: 'GET',
            timeout: '5000',
            cache: false,
            tryCount: 0,
            retryLimit: 3,
            clicked_row_id: clicked_row_id,
            error: 
            function(xhr, textStatus, errorThrown) { 
                if (textStatus == 'timeout') {
                    this.tryCount++;
                    if (this.tryCount <= this.retryLimit) {
                        $.ajax(this); // try again
                        return;
                    }
                }
                        
                if (xhr.status == 500) {
                    // problem with server
                } else {
                    // connection probs?
                } 
                status_alert(gm_lang.label.fetch_email_error);

                back_to_inbox();
                
    		},
            success: 
            function(email) {
    		  
                if (typeof email.mail_id == 'undefined') {
                    status_alert(gm_lang.label.already_deleted);
                    
                    $(clicked_row_id).remove(); // remove this email from the list
                    no_emails_row_check();
                    back_to_inbox();
                    return;
                }

                var html = gm_init_vars.email_template;
                
                html = html.replace(/%INBOX_LINK%/g, '#inbox');
                html = html.replace(/%MAIL_SUBJECT%/g, email.mail_subject);
                html = html.replace(/%MAIL_FROM%/g, email.mail_from);
                html = html.replace(/%MAIL_TO%/g, email.mail_recipient);
                html = html.replace(/%MAIL_DATE%/g, email.mail_date);
                html = html.replace(/%MAIL_BODY%/g, email.mail_body);
 

               $('#display_email').html(html);
    
               $(".email_body a").attr('target', '_blank');// make all the links open in a new window
               
               $("#back_to_inbox_link").unbind('click');
               $("#back_to_inbox_link").click(function (event) {
                    event.preventDefault();
                    back_to_inbox();

                });
                
                if ($(".email_body img").length > 0) {
                    $("#display_images").show();
                    $("#display_images").click( function (event)  {
                        event.preventDefault();
                        
                        var temp_html = $(".email_body").html();
                        
                        // 
                       //res.php?r=1&amp;n=td&amp;q=http%3A%2F%2Fstatic.imvu.com%2Fimvufiles%2Femails%2Fwelcome%2Fgroup_image_3e.jpg&quot;)
                        temp_html = temp_html.replace(/"\/res\.php\?r=1&amp;n=[a-z]+&amp;q=([^"^&]+)"/g, function(str, p1, offset, s) {return unescape (p1); } );
                        temp_html = temp_html.replace(/&quot;\/res\.php\?r=1&amp;n=[a-z]+&amp;q=([^"]+)&quot;/g, function(str, p1, offset, s) {return "&quot;"+unescape(p1)+"&quot;" ; } );
                        
                        $(".email_body").html(temp_html);
                        
                        $("#display_images").hide(2000);
                        
                        
                    });
                    
                }
                
                
               
               $('#display_email').show();
               window.location.hash = "email";
               
               
    		}
    	});
    });
    
}

////////////////////////////////////////////////////////////////////////
// Set a new email address
// Delete all existing messages and re-populate the list

function set_email(email) {
    
    if (email.length < 2) {
        return false;
    }

	$.ajax({
		url: 'http://'+gm_init_vars.ajax_url+'?f=set_email_user',
		dataType: 'json',
		data: {email_user : email, lang: gm_init_vars.lang},
		type: 'GET',
		cache: false,
		error: 
			function(a,b,c) { 

                status_alert(gm_lang.label.set_email_error);
			},
		success: 
			function(result) {
                var email = result.email_addr
                var timestamp = result.email_timestamp
			
  
                change_email(email, timestamp, result.s_active, result.s_date, result.s_time, result.s_time_expires );
                
                back_to_inbox();
                var email_set_str;
                email_set_str = gm_lang.label.email_set.replace('%email%', email);
                status_alert(email_set_str);
                
                if (gm_tick.status==='PAUSED') {
                    gm_tick.status = 'READY';
                }
               
                
                
			}
		});
}


//////////////////////////////////////////

