var Dialogs = {
    init: function () {
        var dbox = $('<div class="paypal-title">Welcome to JobSpice!<br /><br />Would you like to start with a <b>15 second</b> tutorial?</div>');
    
        dbox.infobox({ minWidth: 360,
                   title: "Getting Started",
                   actions: { 
                       Close: function () {
                           dbox.infobox('destroy');
                           $('.name.fn.n').tooltip("Start&nbsp;Here"); 
                           $.cookie('seen_help', 1, { expires: 365 });
                        }
                    },
                    commands: {
                        Yes_Please: function () {
                            dbox.infobox('destroy');
    
                            $('.name.fn.n').tooltip('1)&nbsp;Edit&nbsp;Your&nbsp;Resume', 1000, 2000, 1000);
                            window.setTimeout("$('#editor-add-section').tooltip('2)&nbsp;Add&nbsp;New&nbsp;Sections', 1000, 2000, 1000)", 3000);
                            window.setTimeout("$('#menu-styles').tooltip('3)&nbsp;Select&nbsp;A&nbsp;Style', 1000, 2000, 1000)", 6000);
                            window.setTimeout("$('#toolbar .download').tooltip('4)&nbsp;Download&nbsp;Your&nbsp;Resume', 1000, 2000, 1000)", 9000);
                            // Need to fix
                            window.setTimeout("$('.name.fn.n').tooltip('1)&nbsp;Edit&nbsp;Your&nbsp;Resume', 1000, 2000, 1000); $('#editor-add-section').tooltip('2)&nbsp;Add&nbsp;New&nbsp;Sections', 1000, 2000, 1000); $('#menu-styles').tooltip('3)&nbsp;Select&nbsp;A&nbsp;Style', 1000, 2000, 1000); $('#toolbar .download').tooltip('4)&nbsp;Download&nbsp;Your&nbsp;Resume', 1000, 2000, 1000);", 14000);
                        },
                        Nope: function () {
                            dbox.infobox('destroy');
                            $('.name.fn.n').tooltip("Start&nbsp;Here"); 
                            $.cookie('seen_help', 1, { expires: 365 });
                        }
                    }
                  }).infobox('show');
    },

    help: function (page, refresh) {
        var dbox = eval("Help." + page + "()");
        
        if (refresh) {
           $(".infobox").empty().append(dbox.children());
        } else {
            dbox.infobox({ minWidth: 360,
                       title: "Help",
                       actions: { Close: function () {
                                    dbox.infobox('destroy');
                                            
                                    if (!$.cookie('seen_help')) {
                                        // Set cookie
                                        $.cookie('seen_help', 1, {expires: 365})

                                        $('#toolbar .help').tooltip("Click here to show help.");
                                    }
                                }
                           }
                      }).infobox('show');
        }
    },

    publish_help: function () {
        var dbox =  $('<div class="paypal-title">You\'ve selected a premium style.<br /><br />In order to print, you can either:</div>');
        
        dbox.infobox({ minWidth: 360,
                   title: "Print",
                   actions: { Close: function () {
                                dbox.infobox('destroy');            
                            }
                        },
                   commands: {
                        Buy_This_Style: function() { dbox.infobox('destroy'); State.purchase(); },
                        Choose_A_Free_Style: function() { 
                            dbox.infobox('destroy'); 
                            History.go(function () {
                                State.show_content("styles");
                            });
                        }
                    }
            }).infobox('show');
    },
    
    college_forwarding: function () {
        //if last part of email is .asu.edu then upload link = blah etc
            data = State.user.username;
            var college_check=/csuchico.edu$/
            if (data.search(college_check) != -1) {
                var dbox =  $(
                    '<div class="college-forwarding">' +
                    '<h1>First Draft Complete!</h1>' +
                    '<ul class="functions">' +
                        '<li>' +
                            '<h3>Stop by the Chico State Career Center</h3>' +
                            '<p class="med-title-font grey-one mlz">Please stop by the Career Center and have your ' +
                            'resume reviewed for content by one of our professional career advisors.</p><br />' +
                            '<h3>Drop-In Advising Hours</h3>' +
                            '<p class="med-title-font grey-one mlz">Monday - Friday: 1p – 4p<br /> Or by appointment: (530) 898-5253</p><br />' +
                            '<h3>Location</h3>' +
                            '<p class="med-title-font grey-one mlz">SSC 270</p>' +
                            '<br /><p class="med-title-font grey-two mlz">Make your career search a success with our database of local, national and international jobs and internships. Stop by the Career Center today to set up your account. </p><div class="cb"></div>' +
                        '</li>' +
                    '</ul>' +
                    '<br />' +
                    '</div>');

                dbox.infobox({  minWidth: 330,
                                minHeight: 440,
                                title: "Congratulations",
                                actions: { Close: function () {
                                    dbox.infobox('destroy');
                                    //$.cookie('seen_word_help', null, { path: '/',  expires: -1 });
                                    }
                                },
                                commands:{ Keep_Editing_Resume: function(){
                                    dbox.infobox('destroy');
                                    }}
                                }).infobox('show');
                } /* else {                                         // this needs to stay here - it's for other colleges, and we'll use it really soon!
                    var dbox =  $(
                            '<div class="college-forwarding">' +
                                '<h1>Congrats! Next Up:</h1>' +
                                '<ul class="functions">' +
                                    '<li>' +
                                        '<div class="icon-wrapper search round-10px">' +
                                            '<img src="/static/css/images/ajaxloader/search.jpg" />' +
                                        '</div>' +
                                        '<h3>Start the Job Search</h3>' +
                                        '<p class="med-title-font grey-one"><a>Upload your resume</a> to the career center database</p><div class="cb"></div>' +  
                                    '</li>' +
                                    '<li>' +
                                        '<div class="icon-wrapper pdf round-10px">' +
                                            '<img src="/static/css/images/ajaxloader/pdf.jpg" />' +
                                        '</div>' +
                                        '<h3>Career Guides</h3>' +
                                        '<p class="med-title-font grey-one">Read through these <a>helpful guides</a> for great advice</p><div class="cb"></div>' +
                                    '</li>' +
                                    '<li>' +
                                        '<div class="icon-wrapper internet round-10px">' +
                                            '<img style="margin: 4px 0 0 7px;" src="/static/css/images/ajaxloader/help.jpg" />' +
                                        '</div>' +
                                        '<h3>Career Counseling</h3>' +
                                        '<p class="med-title-font grey-one"><a>Set up an appointment</a> with a career counselor</p><div class="cb"></div>' +
                                    '</li>' +
                                '</ul>' +
                                '<br />' +
                            '</div>');

                dbox.infobox({ minWidth: 330,
                               minHeight: 480,
                               title: "Career Center Options",
                               actions: { Close: function () {
                                            dbox.infobox('destroy');
                                            //$.cookie('seen_word_help', null, { path: '/',  expires: -1 });
                                        }
                                   },
                                   commands:{ Keep_Editing_Resume: function(){
                                            dbox.infobox('destroy');
            
                                   }}
                              }).infobox('show');
                }*/
    },

    help_word_update: function () {
        var dbox =  $(
                    '<div class="update-resume">' +
                        '<p class="full"><strong>Restyling an old resume takes less than 5 minutes!</strong></p>' +
                        '<h2 class="round_5px">1</h2>' +
                        '<p>Open your resume in Word</p>' +
                        '<h2 class="round_5px">2</h2>' +
                        '<p>For each section in your resume, create a corresponding section in Jobspice by clicking the "Add section" button in the Jobspice tool</p>' +
                        '<h2 class="round_5px">3</h2>' +
                        '<p>Just copy the information from your old resume into the correct fields on Jobspice</p>' +
                        '<h2 class="round_5px">4</h2>' +
                        '<p>Click the design tab, choose a design, and watch Jobspice completely restyle your resume!</p>' +
                        '<br class="clear" />' +
                    '</div>');
        
        dbox.infobox({ minWidth: 330,
                       title: "Update Your Resume",
                       actions: { Close: function () {
                                    dbox.infobox('destroy');
                                    $.cookie('seen_word_help', null, { path: '/',  expires: -1 });
                                }
                           }
                      }).infobox('show');
    },

    login: function () {
        var dbox = $('<div />');
        
        var message = $('<p class="center error" />').hide();
        var username_input = $('<input type="text" class="text" name="username" maxlength="50" />');
        var password_input = $('<input type="password" class="text" name="password" maxlength="16" />');
        
        dbox.append(message);
        dbox.append($('<div><label>Email</label></div>').prepend(username_input).clearFloats());
        dbox.append($('<div><label>Password</label></div>').prepend(password_input).clearFloats());
        dbox.append($('<div class="forgot-login-box"><a href="/password">Forgot Password?</a></label></div>').clearFloats());
        
        dbox.infobox({ minWidth: 330,
                       title: "Login",
                       actions: { Close: function () { dbox.infobox('destroy'); } },
                       commands: {
                           Login: function () {
                               dbox.infobox('start_loading');
                               
                               var fn = function () {
                                    dbox.infobox('destroy');
                               };
                               
                               var fn_error = function (data) {
                                    message.text(data.error_message);
                                    message.show();
                                    dbox.infobox('finish_loading');
                               };
                               
                               State.try_login(username_input.val(), password_input.val(), true, fn, fn_error);
                           }
                       }
                     }).infobox("show");
       
        username_input.trigger('focus');             
        password_input.keydown( function (e) {
            if (e.keyCode == 13) {
                $('.infobox-commands .login').trigger('click');
                return false;
            }
        });
    },

    load_overwrite: function (load_fn) {
            var dbox = $('<div />');

            var overwrite_button = $('<input type="button" class="button" value="Load Saved" />');
            var cancel_button = $('<input type="button" class="button" value="Make New Resume" />');
        
            dbox.append('<p class="center error">Are you writing a new resume? (JobSpice already has a saved resume on file) Clicking "Make New Resume" will <u>erase</u> your saved resume!</p>');
            dbox.append($('<div class="center" />').append(overwrite_button)
                                                   .append(cancel_button)
                                                   .clearFloats());
        
            dbox.infobox({ minWidth: 300,
                           title: "Replace changes?",
                           actions: { Close: function () {
                                        dbox.infobox('destroy');
                                    }
                               }
                         }).infobox("show");

            overwrite_button.bind('click', function () { dbox.infobox('destroy'); load_fn(); });
            cancel_button.bind('click', function () { dbox.infobox('destroy'); });
    },

    logout_discard: function () {
        var dbox = $('<div />');

        dbox.append('<p class="center error">Are you sure you want to logout and discard your unsaved changes?</p>');
        
        dbox.infobox({ minWidth: 300,
                       title: "Discard changes?",
                       actions: { 
                           Close: function () {
                               dbox.infobox('destroy');
                           }
                       },
                       commands: {
                           Discard: function () {
                               dbox.infobox('destroy'); State.logout(true);
                           },
                           Cancel: function () {
                               dbox.infobox('destroy');
                           }
                       }
                     }).infobox("show");
    },

    publish: function () {
        // Need to change to download_options
        var dbox = $('<ul id="publishing_options">' +
                        '<li><a class="pdf"></a></li>' +
                        '<li><a class="docx"></a></li>' +
                     '</ul>');

        dbox.infobox({ minWidth: 350,
                       title: "Download Options",
                       actions: { Close: function () { dbox.infobox('destroy'); } }
                      }).infobox('show');

        $('#publishing_options .pdf').action("Download a PDF of your Resume", State.pdf, "pdf").bind('click', function () { dbox.infobox('destroy'); });
        $('#publishing_options .docx').action("Convert the content of your resume into a DOCX", State.docx, "docx").bind('click', function () { dbox.infobox('destroy'); });
    },
    
    register: function (type) {
        if (type == "save") { 
            var _title = "Save changes";
            var message = $('<p class="error">Please Register to Save Changes</p>');
        }
        
        else if (type == "signup") {
            var _title = "Sign Up";
            var message = $('<p class="error">Sign Up for Your Free Account</p>');
        
        } else {
            var _title = "Sign Up"
            var message = $('<p class="error">Please Register to Print your Resume</p>');
        }
                        
        var dbox = $('<div />');
        var username_input = $('<input type="text" class="text" name="username" maxlength="50" />');
        var password_input = $('<input type="password" class="text" name="password" maxlength="16" />');
        var url_input = $('<input type="text" class="text" name="url" maxlength="127" style="padding-left: 115px; width: 170px;"/>');
        var graduation_year_input = $('<div style="display: none;"><select id="college-graduation-year" class="round-3px big"></select><div><label>Class</label></div></div>');
        
        dbox.append(message);
        dbox.append($('<div><label>Email</label></div>').prepend(username_input).clearFloats());
        dbox.append($('<div><label>Password</label></div>').prepend(password_input).clearFloats());
        dbox.append($('<div style="height: 54px;"><label>Profile URL</label></div>').append('<div class="fieldhint">jobspice.com/</div>').prepend(url_input).clearFloats());
        dbox.append(graduation_year_input).clearFloats();
        $('.close').addClass('round_3px');


        var dt = new Date();
        var my_time = dt.getFullYear();
        
        for (i=0; i < 5; i++) {
            $(graduation_year_input).find('select').prepend('<option value=' + '"' +  my_time + '"' + '>' + my_time + '</option>');
            my_time = my_time + 1;
        }

        var is_student = false;

        username_input.trigger('focus').bind('keyup', function(e) {
            var valid_schools = ["uw.edu", "u.washington.edu","edison.edu","email.socc.edu", "socc.edu","asu.edu","umail.ucsb.edu", "sa.ucsb.edu","northwestern.edu","hartford.edu","avc.edu","bellevuecollege.edu","hawaii.edu","hancockcollege.edu","mail.csuchico.edu", "csuchico.edu","brevard.cc.fl.us","uri.edu", "my.uri.edu","coastline.edu","citruscollege.edu","cocc.edu","osu.edu","gcu.edu","sjsu.edu","elcamino.edu","utoronto.ca","liberty.edu", "smu.edu"];
            var user = $('input[name="username"]').val();

            $.each(valid_schools, function(i, email) {
                var re = new RegExp(email + "$","g");
                if (user.match(re) != null) { is_student = true; }
            });
        
            if (is_student) {
                $('.infobox-outer').css('height', '390px'); // 330px
                $('#college-graduation-year').fadeIn(1000);

            }
        });

        password_input.keydown(function (e) {
            if (e.keyCode == 13) {
                $('.infobox-commands a.register').trigger('click');
                return false;
            }
        });
        
        dbox.infobox({ minWidth: 330,
                       title: _title,
                       actions: { 
                           Close: function () {
                                dbox.infobox('destroy');
                            }
                        },
                        commands: {
                            Register: function () {
                                dbox.infobox('start_loading');
                                
                                var graduation_year = (is_student ? $('#college-graduation-year').val() : "None" );
                                var url = ($('input[name="url"]').val() ? $('input[name="url"]').val() : "None");
                                
                                var resume = State.resume;
                                var style = State.current_style;
                                
                                $.ajax({
                                    type: "GET",
                                    url: "/data/" + style.template + "/template.html",
                                    dataType: "html",
                                 
                                    success: function (html) {
                                        var template = $('<div />').append(html);
                                        template.find('.object.resume').render(resume);
                                        template.find('.object.resume').removeEmpty();
                                             
                                        var xhtml = template.find('.object.resume').outerHTML();
                                        var title = template.find('h1').text();

                                        $.ajax({
                                            type: "POST",
                                            url: "ajax/register",
                                            dataType: "json",
                                            data:jsonify({
                                                username: username_input.val(),
                                                password: password_input.val(),
                                                url: url,
                                                resume_data: resume,
                                                xhtml: xhtml,
                                                title: title,
                                                graduation_year: graduation_year
                                            }),
                                            
                                            success: function (data) {
                                                State.login();
                                                
                                                State.available_styles = data[0];
                                                State.profile_url = data[1];
                                                
                                                dbox.infobox('destroy');

                                                if (!data) {
                                                    Dialogs.save_overwrite();
                                                } else {
                                                    State.save(false);

                                                    if (type == "pdf") { Dialogs.generate_pdf(); }
                                                    if (type == "docx") { Dialogs.generate_docx(); }
                                                    if (type == "purchase") { Dialogs.purchase(); }
                                                };
                                            },
                                            
                                            error: function (xhr, status, e, data) {
                                                if (!data) { data = { error_message: "Connection Error" }; }
                                                message.text(data.error_message);
                                                dbox.infobox('finish_loading');
                                            } 
                                        });
                                    }
                                });
                            }
                        }
                            
        }).infobox("show");
    },
    
    resend_email: function (current_email) {
        var dbox =  $('<div style="font-size: 13px; text-align:center;">A confirmation email has been sent to ' + current_email + '</div>');
        dbox.infobox({ minWidth: 310,
                       title: "Resent Email",
                       actions: { Close: function () { dbox.infobox('destroy'); } }
                      }).infobox('show');

        State.save(false);

    },

    why_update_username: function () {
        var dbox =  $('<div style="font-size: 13px; text-align:left;">Since JobSpice has been growing at a remarkable pace, we needed a better way to communicate with our users and standardize that communication process, so we have switched from using usernames to email addresses for accounts.<br /><br /><b>We will never spam you.</b><br /><br />We love helping our users out, and this change will help us do that more efficiently. If you have questions, please feel free to email us at contact@jobspice.com.<div style="margin-top: 20px;">The JobSpice Team</div></div>');
        
        dbox.infobox({ minWidth: 310,
                       title: "Account Update",
                       actions: { Close: function () { dbox.infobox('destroy'); } }
                      }).infobox('show');
    },

    change_email: function (current_email) {
        var email_check = current_email.match(/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/);
        if (email_check != null) {
            var dialog = 'Current Email Address'
            var dialog_new = 'New Email Address'
        } else {
            var dialog = 'Current Username'
            var dialog_new = 'Email Address (Your new username)'
        }


        var dbox =  $(
            '<div>' +
                '<span style="font-size:13px; font-weight:bold; margin-left:10px;">' + current_email + '</span><label>' + dialog + '</label>' +
                '<input type="text" class="text new_username"></input><label>' + dialog_new + '</label>' +
                '<div class="cb"></div>' +
            '</div>');
        
        dbox.infobox({ minWidth: 400,
                       title: "Update Email",
                       actions: { Close: function () { dbox.infobox('destroy'); } },
                       commands: {
                           Update: function () {
                                $.ajax({
                                    type: "POST",
                                    url: "/ajax/set_username",
                                    dataType: "json",
                                    data: jsonify({
                                        new_username: $('.infobox input.new_username').val()
                                    }),
                                    error: function (xhr, status, e, data) { },
                                    success: function (data) { dbox.infobox('destroy'); State.save(false); }
                                });
                           },
                           Cancel: function () {
                               dbox.infobox('destroy');
                           } }
                       }).infobox('show');
                      
    },

    save_overwrite: function () {
        var dbox = $('<div />');
        var message = $('<p class="center error">Are you sure you want to overwrite your saved data?</p>');
        
        dbox.append(message);
        
        dbox.infobox({ minWidth: 260,
                       title: "Overwrite saved data?",
                       actions: {
                           Close: function () {
                                State.logout(); 
                                dbox.infobox('destroy');
                            }
                        },
                        commands: {
                            Overwrite: function () {
                                State.save(false); dbox.infobox('destroy');
                            },
                            Cancel: function () {
                                State.logout(); dbox.infobox('destroy');
                            }
                        }
                     }).infobox("show");
    },

    update_permalink: function () {
        // var url_input = $('<input type="text" class="text" name="url" maxlength="127" style="padding-left: 115px; width: 170px;"/>');
        // dbox.append($('<div style="height: 54px;"><label>Profile <span style="color: #333; font-weight: bold;">(Optional)</span></label></div>').append('<div class="fieldhint">jobspice.com/</div>').prepend(url_input).clearFloats());

        var dbox = $('<div />');
        var error = $('<p class="center big" />').hide();
        var message = $('<p class="center big" />').hide();

        dbox.append(error);
        dbox.append(message);
        dbox.infobox({ minWidth: 325,
                       title: "Your Profile",
                       actions: { Close: function () { dbox.infobox('destroy'); } }
                    }).infobox('start_loading').infobox('show');
        
        message.append("<div class='main_text'> Would you like to update your resume?</div>");
        var continue_button = $('<input type="submit" class="submit" value="No thanks" style="margin-top: 20px;" />');
        var update_button = $('<input type="submit" class="submit" value="Yes, update my profile" style="margin-top: 20px;" />');
        

        submit_button.bind('click', function () {
            dbox.infobox('start_loading');
        
            var resume = State.resume;
            var style = State.current_style;

            $.ajax({
                type: "GET",
                url: "/data/" + style.template + "/template.html",
                dataType: "html",

                success: function (html) {
                    var template = $('<div />').append(html);
                    template.find('.object.resume').render(resume);
                    template.find('.object.resume').removeEmpty();
            
                    var xhtml = template.find('.object.resume').outerHTML();
                    var title = template.find('h1').text();
    
                    $.ajax({
                        type: "POST",
                        url: "ajax/create_profile",
                        dataType: "json",
                        data: jsonify({
                            resume_data: resume,
                            current_style: style.key_name,
                            xhtml: xhtml,
                            title: title,
                            url: url
                        }),
        
                        success: function (data) {
                            var link = $('<a />');
                            var href = 'http://www.jobspice.com/' + url;
                            link.text(href);
                
                            link.bind('click', function () {
                                window.open(href);
                                return false;
                            });
        
                            dbox.children().hide();
                            message.attr('class', 'center big');
                            message.empty().append(link);
                            message.show();

                            dbox.infobox('finish_loading');
                        },
        
                        error: function (xhr, status, e, data) {
                            if (!data) { data = { error_message: "Connection Error" }; }
            
                            message.attr('class', 'center error');
                            message.text(data.error_message);
                            message.show();
                    
                            dbox.infobox('finish_loading');                        
                        }
                    });
                }
            });

            return false;
        });
    },
    
    generate_pdf: function () {
        var dbox = $('<div />');
        var error = $('<p class="center big" />').hide();
        var message = $('<p class="center big" />').hide();

        dbox.append(error);
        dbox.append(message);
        dbox.infobox({ minWidth: 325,
                       title: "Generating PDF",
                       actions: { Close: function () { dbox.infobox('destroy'); } }
                    }).infobox('start_loading').infobox('show');

        var resume = State.resume;
        var style = State.current_style;

        $.ajax({
            type: "GET",
            url: "/data/" + style.template + "/template.html",
            dataType: "html",

            success: function (html) {
                var template = $('<div />').append(html);
                template.find('.object.resume').render(resume);
                template.find('.object.resume').removeEmpty();
    
                var xhtml = template.find('.object.resume').outerHTML();
                var title = template.find('h1').text();
                title = (title ? title : "Resume");

                $.ajax({
                    type: "POST",
                    url: "ajax/pdf",
                    dataType: "json",
                    data: jsonify({
                        resume_data: resume,
                        current_style: style.key_name,
                        xhtml: xhtml,
                        title: title
                    }),

                    success: function (data_key) {
                        var link = $('<a>Click here to download PDF.</a>');
                        var href = 'http://www.jobspice.com/' + 'data' + '/' + data_key + '/' + title + '.pdf';
            
                        link.bind('click', function () {
                            if($.browser.msie) {
                                title = title.replace(/[^a-z0-9]/ig, "");
                            }

                            dbox.infobox('destroy');
                            
                            // Handles if the user comes from a college landing page
                            if($.cookie('college_forwarding')) {
                                $.cookie('college_forwarding', null, { path: '/',  expires: -1 });
                                Dialogs.college_forwarding();
                            }

                            window.open(href, title, "menubar=0,location=0,status=0,scrollbars=1,width=1000");
                            return false;
                        });

                        message.empty().append(link);
                        message.show();

                        dbox.infobox('finish_loading');
                    },

                    error: function (xhr, status, e, data) {
                        if (!data) { data = { error_message: "Connection Error" }; }
    
                        message.text(data.error_message);
                        message.show();
            
                        dbox.infobox('finish_loading');                        
                    }
                });
            }
        });
    },
    
    generate_docx: function () {
        var dbox = $('<div />');
        var error = $('<p class="center big" />').hide();
        var message = $('<p class="center big" />').hide();

        dbox.append(error);
        dbox.append(message);
        dbox.infobox({ minWidth: 325,
                       title: "Generating DOCX",
                       actions: { Close: function () { dbox.infobox('destroy'); } }
                    }).infobox('start_loading').infobox('show');

        var resume = State.resume;

        $.ajax({
            type: 'POST',
            url: 'ajax/is_docx_compatible',
            dataType: 'json',
            data: jsonify({
                current_style: State.current_style.key_name
            }),
    
            success: function(style) {
                $.ajax({
                    type: "GET",
                    url: "/data/" + style.template + "/template.html",
                    dataType: "html",

                    success: function (html) {
                        var template = $('<div />').append(html);
                        template.find('.object.resume').render(resume);
                        template.find('.object.resume').removeEmpty();
    
                        var xhtml = template.find('.object.resume').outerHTML();
                        var title = template.find('h1').text();
                        title = (title ? title : "Resume");

                        $.ajax({
                            type: "POST",
                            url: "ajax/docx",
                            dataType: "json",
                            data: jsonify({
                                resume_data: resume,
                                current_style: style.key_name,
                                xhtml: xhtml,
                                title: title
                            }),

                            success: function (data_key) {
                                var link = $('<a>Click here to download docx.</a>');
                                var href = 'http://www.jobspice.com/' + 'data' + '/' + data_key + '/' + title + '.docx';
            
                                link.bind('click', function () {
                                    if($.browser.msie) {
                                        title = title.replace(/[^a-z0-9]/ig, "");
                                    }

                                    dbox.infobox('destroy');
                        
                                    // Handles if the user comes from a college landing page
                                    if($.cookie('college_forwarding')) {
                                        $.cookie('college_forwarding', null, { path: '/',  expires: -1 });
                                        Dialogs.college_forwarding();
                                    }

                                    window.open(href, title, "menubar=0,location=0,status=0,scrollbars=1,width=1000");
                                    return false;
                                });

                                message.empty().append('<p style="font-size: 13px; margin-bottom: 10px;">Your style is being converted to Word. Fonts, colors and spacing may be altered in the conversion process.</p>').append(link);
                                message.show();

                                dbox.infobox('finish_loading');
                            },

                            error: function (xhr, status, e, data) {
                                if (!data) { data = { error_message: "Connection Error" }; }
    
                                message.text(data.error_message);
                                message.show();
            
                                dbox.infobox('finish_loading');                        
                            }
                        });
                    }
                });            
            }
    
        });
    }, 

    purchase: function() {
        State.save(false);
        
        var dbox = $('<div />');
        var error = $('<p class="center big" />').hide();
        var message = $('<p class="center big" />').hide();
        
        dbox.append(error);
        dbox.append(message);
        dbox.infobox({ minWidth: 325,
                       title: "Premium Style",
                       actions: { Close: function () { dbox.infobox('destroy'); } }
                    }).infobox('start_loading').infobox('show');

        message.append("<div class='paypal-title'> You've selected a premium style: <b>" + State.current_style.title + "</b><br /><br />Own this style for just <b>$" + State.current_style.price + "</b>, and help us feed our programmers! <br /><br /></div>");
        //message.append("<div class='paypal-desc'>You can buy this style for just $" + State.current_style.price + "</div>");

        var promo_code = "";

        // Make sure that if the style is a custom style, you grab the partent style key_name
        var style_key_name = State.current_style.key_name;
        if (State.current_style.parent_style) { style_key_name = State.current_style.parent_style; }

        var custom = $.cookie('user') + ';' + style_key_name;
        var link_el = $('<form class="paypal-form" action="https://www.paypal.com/cgi-bin/webscr" method="post">' +
                    '<input type="hidden" name="cmd" value="_xclick">' +
                    '<input type="hidden" name="business" value="RUC8F96K8KWPY">' + // RUC8F96K8KWPY // TDCWDXZVTKHV2
                    '<input type="hidden" name="lc" value="US">' +
                    '<input type="hidden" name="item_name" value="Premium Style">' +
                    '<input type="hidden" name="amount" value="' + State.current_style.price + '">' +
                    '<input type="hidden" name="currency_code" value="USD">' +
                    '<input type="hidden" name="button_subtype" value="products">' +
                    '<input type="hidden" name="no_note" value="1">' +
                    '<input type="hidden" name="no_shipping" value="1">' +
                    '<input type="hidden" name="tax_rate" value="0.000">' +
                    '<input type="hidden" name="shipping" value="0.00">' +
                    '<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHosted">' +
                    '<input type="hidden" name="notify_url" value="http://www.jobspice.com/paypal_ipn">' +
                    '<input type="hidden" name="return" value="http://www.jobspice.com/thanks">' +
                    '<input type="hidden" name="cancel_return" value="http://www.jobspice.com/home">' +
                    '<input type="hidden" name="custom" value="' + custom + '">' +
                    '<input type="submit" id="paypal_button" border="0" name="submit" value="">' + // src="/static/css/images/paypal-buy.gif"
                    '<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">' +
                    '</form>');

        message.append(link_el);

        $('#paypal_button').bind('click', function() { 
            dbox.infobox('destroy');
            State.start_loading();
            State.update_loading(40, "Transferring to PayPal");
        });

        // var promo_el = $('<input id="promo" type="text" size="20" style="font-size: 14px" value="Apply School Code" style="clear: both;" />');                
        // message.append(promo_el);
        // 
        // $('#promo').bind('click', function() { 
        //     if ($('#promo').val() == 'Apply School Code') {
        //         $('#promo').val('').css({
        //             'color': '#333'
        //         });
        //     }
        // }).bind('blur', function () {
        //     if ($('#promo').val() == '') {
        //         $('#promo').val('Apply School Code').css({
        //             'color': '#bbb'
        //         });
        //     }
        // });
        // 
        // var button_el = $('<input class="submit apply paypal-submit" type="submit" value="Apply" />');
        // message.append(button_el);

        message.append("<div class='paypal-last-text'>Transactions use PayPal's <b>secure</b> payment system</span></div><div class='cb'></div>");

        //var paypal_seal = '<a id="paypal_seal" href="https://www.paypal.com/us/verified/pal=dane%40jobspice%2ecom" target="_blank"><img src="https://www.paypal.com/en_US/i/icon/verification_seal.gif" border="0" alt="Official PayPal Seal"></a>';
        //message.append(paypal_seal);

        // $(button_el).bind('click', function() { 
        //     if (!$(this).hasClass('selected')) {
        //         $(this).addClass('selected');
        // 
        //         $.ajax({
        //             type: "POST",
        //             url: "ajax/get_promotion",
        //             dataType: "json",
        //             data: jsonify({
        //                 promo: $("#promo").val()
        //             }),
        //             error: function (xhr, status, e, data) {
        //                 $("#promo").val('');
        //                 $('.apply').removeClass('selected');
        //                 if (!data) { data = { error_message: "Connection Error" }; }
        //                 error.text(data.error_message).show();
        //                 dbox.infobox('finish_loading');
        //             },
        //             success: function(promo){
        //                 dbox.infobox('destroy');
        //                 State.available_styles.push(State.current_style);
        //                 State.select_style(State.current_style);
        //                 Dialogs.publish();
        //             }
        //         });
        //         return false;
        //     }
        // });

        message.show();
        dbox.infobox('finish_loading');
    },
    
    customize_margins: function () {
        var dbox = $('<div></div>');

        var top_input = $('<input type="text" class="text" name="top" maxlength="4" />');
        dbox.append(top_input).append($('<div><label>Top (in.)</label></div>').clearFloats());

        var left_input = $('<input type="text" class="text" name="left" maxlength="4" />');
        dbox.append(left_input).append($('<div><label>Left (in.)</label></div>').clearFloats());

        var right_input = $('<input type="text" class="text" name="right" maxlength="4" />');
        dbox.append(right_input).append($('<div><label>Right (in.)</label></div>').clearFloats());

        var bottom_input = $('<input type="text" class="text" name="bottom" maxlength="4" />');
        dbox.append(bottom_input).append($('<div><label>Bottom (in.)</label></div>').clearFloats());

        var input_el = $('<div class="center"></div>');
        
        var apply_button = $('<input type="button" class="button" value="Apply" />');
        input_el.append(apply_button);
        apply_button.bind('click', function () { State.customize(type, [top_input.val(), right_input.val(), bottom_input.val(), left_input.val()]); dbox.infobox('destroy'); });

        dbox.append(input_el);

        //$('#preview-iframe').ifind('.hresume').css('padding-left');
        //State.custom_css['#' + $(el).attr('id')]['padding-top']

        var el = $('#preview-iframe').ifind('.hresume');

        // Populate Input Fields

        if (parseFloat($('#preview-iframe').ifind('.hresume').css('padding-left'))) {
            var type = 'padding';
        } else {
            var type = 'margin';
        }

        if ($('#preview-iframe').ifind('.hresume').css('padding-left').match(/in/)) {
            var normalize = 1;
        } else {
            var normalize = 96;
        }

        if (!State.custom_css['#'+ $(el).attr('id')])
            State.custom_css['#'+ $(el).attr('id')] = {};

        if (State.custom_css['#' + el.attr('id')][type+'-top']) {
            var size = State.custom_css['#' + el.attr('id')][type+'-top'].replace('in','');
        } else {
            var size = parseInt(el.css(type+'-top')) / normalize;
        }
        top_input.val(size);

        if (State.custom_css['#' + el.attr('id')][type+'-left']) {
            var size = State.custom_css['#' + el.attr('id')][type+'-left'].replace('in','');
        } else {
            var size = parseInt(el.css(type+'-left')) / normalize;
        }
        left_input.val(size);

        if (State.custom_css['#' + el.attr('id')][type+'-right']) {
            var size = State.custom_css['#' + el.attr('id')][type+'-right'].replace('in','');
        } else {
            var size = parseInt(el.css(type+'-right')) / normalize;
        }
        right_input.val(size);

        if (State.custom_css['#' + el.attr('id')][type+'-bottom']) {
            var size = State.custom_css['#' + el.attr('id')][type+'-bottom'].replace('in','');
        } else {
            var size = parseInt(el.css(type+'-bottom')) / normalize;
        }
        bottom_input.val(size);

        dbox.infobox({ minWidth: 320,
                       title: "Margins",
                       actions: { Close: function () { dbox.infobox('destroy'); } }
                       }).infobox('show');
    },
    
    reset_style: function () {
        var dbox = $('<div />');

        dbox.append('<p class="center error">Are you sure you want to reset to this style\'s default design?</p>');

        dbox.infobox({ minWidth: 260,
                       title: "Reset to default?",
                       actions: { Close: function () { dbox.infobox('destroy'); } },
                       commands: {
                            Yes: function () {
                                dbox.infobox('destroy'); 
                                $.ajax({
                                    type: "POST",
                                    url: "ajax/reset_style",
                                    dataType: "json",
                                    data: jsonify({
                                        current_style: State.current_style.key_name
                                    }),

                                    success: function (data) {
                                        State.recent_styles = State.recent_styles.slice(1, 10);
                                        State.select_style(data);
                                        State.custom_css = {};
                                        State.show_content('preview');
                                    },

                                    error: function (xhr, status, e, data) {
                                        if (!data) { data = { error_message: "Connection Error" }; }
                                    }
                                });
                            },
                            Cancel: function () {
                                 dbox.infobox('destroy');
                            }
                        }
                     }).infobox("show");
    }
};
