﻿var Extra = {
    ApplyForProject: function(objSender, _projectID) {

        objSender.disabled = true;
        objSender.value = 'Please Wait';

        var _profileID = $F('applyProfiles');


        if (_profileID == '-1') {
            alert("You must choose a profile to apply.");
            objSender.disabled = false;
            objSender.value = 'Submit Profile';
            return;
        }

        if (_profileID == 'inactive') {
            alert("Inactive Profiles may not be submitted for projects.  Please activate this profile.");
            objSender.disabled = false;
            objSender.value = 'Submit Profile';
            return;
        }


        new Ajax.Request('Content/Data/ApplyForProject.ashx',
      {
          parameters: { user_id: $F('user_id'), profile_id: _profileID, project_id: _projectID },
          onSuccess: function(response) {
              alert('Your profile has been successfully submitted to the site.  You should receive an email confirmation shortly.');
              Dialogs.close();
          }
      });

    },

    ChangeShowHelp: function(tf) {
        new Ajax.Request('Data/PersonDataUpdate.ashx',
      {
          parameters: { user_id: $F('user_id'), show_help: tf },
          onSuccess: function(response) {

          }

      });
    },

    ImportProfile: function() {
        var uid, pwd, bdate;
        uid = $F('oldUserName');
        pwd = $F('oldPassword');
        bdate = $F('oldBirthDate');

        if (uid.value == "") {
            alert('Username is required');
            return;
        }

        if (pwd.value == "") {
            alert('Password is required');
            return;
        }

        if (bdate.value == "") {
            alert('Birthdate is required');
            return;
        }

        var profile;
        // we got 'em, lets submit it
        new Ajax.Request('Data/ImportOldProfile.ashx',
        {
            parameters: { user_id: $F('user_id'), user_name: uid, password: pwd, birth_date: bdate },
            onSuccess: function(response) {



                if (response.responseText == "ERROR") {
                    alert("There was a problem importing your profile, please contact us at Feedback@utahextras.com.\nPlease send us your email address used on the old site, and your User Name.\nNEVER GIVE OUT YOUR PASSWORD TO ANYONE\nWe will never EVER ask you for your password.");
                    return;
                }

                if (response.responseText == "DUPLICATE") {
                    alert("This profile already exists in the system.  If this is in error please contact us immediately.");
                    return;
                }

                if (response.responseText == "FAIL") {
                    alert("Incorrect information has been provided, please try again.");
                    Dialogs.close();
                    return;
                }
                else {
                    profile = response.responseText.evalJSON();
                    $('myProfilesContainer').insert(Extra._defaultSummaryRow(profile));
                    Dialogs.close();
                }

            }
        });



    },

    ShowImportProfile: function() {
        var x = '';
        x += '<div style="height: 600px; width: 600px;">';
        x += '<table style="color: black;">';
        x += '<tr>';
        x += '<td valign="top">Old UserName:</td><td valign="top"><input type="text" id="oldUserName"/></td>';
        x += '</tr>';
        x += '<tr>';
        x += '<td valign="top">Old Password</td><td valign="top"><input type="password" id="oldPassword"/></td>';
        x += '</tr>';
        x += '<tr>';
        x += '<td valign="top">Birthdate of old profile</td><td><input type="text" id="oldBirthDate"/></td>';
        x += '</tr>';
        x += '<tr>';
        x += '<td>I agree to the Terms of Service (TOS)</td><td><input type="checkbox" id="chkTOS" onclick="if(this.checked){this.value=DateFormat.format(new Date(), \'MM/dd/yyyy HH:mm:ss\');}else{this.value=\'\';}"/></td>';
        x += '</tr>';
        x += '<tr>';
        x += '<td>I have read the Privacy Statement</td><td><input type="checkbox" id="chkPrivacy"  onclick="if(this.checked){this.value=DateFormat.format(new Date(), \'MM/dd/yyyy HH:mm:ss\');}else{this.value=\'\';}"/></td>';
        x += '</tr>';
        x += '</table>';
        x += '<input type="button" value="Import Profile" onclick="Extra.ImportProfile();"/>';
        x += '<input type="button" value="Cancel/Close" onclick="Dialogs.close();" />';
        x += '</div>';
        new Dialog({ title: 'Import old profile', content: x, width: 600, height: 600, close: { link: false, overlay: false, esc: true} }).open();



    },

    Delete: function(key) {
        var result;
        var confirmed = confirm("Are you sure you wish to delete this profile?\nNo refund will be issued.");
        if (confirmed) {
            new Ajax.Request('Data/Extra_Delete.ashx', {
                parameters: { user_id: $F('user_id'), key: key },
                onSuccess: function(response) {
                    result = response.responseText.evalJSON();
                    if (result.response == true) {
                        // remove the row
                        $('row_' + result.row_id).remove();
                    }
                }

            });

        }
    },

    _defaultSummaryRow: function(profile) {
        /*<td>ID</td>
        <td>Edit/Delete</td>
        <td>Profile Name</td>
        <td>Birth Date</td>
        <td>Status</td>*/
        var x = '';
        x += '<tr id="row_' + profile.ExtraProfileID + '" class="' + (profile.ExpireDate < new Date() ? 'Expired' : 'Active') + '"><td>';
        x += profile.ExtraProfileID;
        x += '</td><td>';
        x += '<span class="link"><a href="AddEditExtra.aspx?z=' + profile.Key + '"><img border="none" src="../images/pencil.png" alt="Edit" /></a></span>';
        x += ' / ';
        x += '<span class="link" onclick="Extra.Delete(\'' + profile.ExtraProfileID + '\');"><img src="../images/delete.png" alt="Delete" /></span>';
        x += '</td><td>';
        x += profile.FullName;
        x += '</td><td>';
        x += formatDate(profile.BirthDate, "MM/dd/yyyy");
        x += '</td><td>';
        //x += profile.ExpireDate + "~" + new Date();
        x += (profile.ExpireDate < new Date() ? '<a href="ActivateProfile.aspx?z=' + profile.Key + '">Inactive and not eligible for Jobs<br /> (Click here to Activate now!)</a>' : 'Active until ' + formatDate(profile.ExpireDate, "MM/dd/yyyy"));
        x += '</td></tr>';

        return x;
    },

    LoadForUser: function(userID) {
        if (userID == null)
            userID = $F('user_id');
        var profiles;
        new Ajax.Request('Data/Extra_Load.ashx',
        {
            parameters: { user_id: userID },
            onSuccess: function(response) {
                profiles = response.responseText.evalJSON();
                /* if ($F('showHelp') == "on") {
                ShowMembershipVsProfile();
                }*/

               // $('myProfilesContainer').clear();
                
                profiles.each(function(p) {
                    $('myProfilesContainer').insert(Extra._defaultSummaryRow(p));
                });
            }

        });

    },

    Save: function() {
        // some validation
        //$('btnSave').toggle();

        if ($('accntOwnerFirstName') != null) {

            // contact info is required.
            if ($F('accntOwnerFirstName') == null || $F('accntOwnerFirstName') == '') {
                alert('Account owner first name is required.');
                document.getElementById('accntOwnerFirstName').focus();
                return;
            }

            if ($F('accntOwnerLastName') == null || $F('accntOwnerLastName') == '') {
                alert('Account owner last name is required.');
                document.getElementById('accntOwnerLastName').focus();
                return;
            }


            if ($F('mobilePhone').length > 0) {
                if ($F('mobileCarrier') == '-1') {
                    alert('If you specify a mobile phone, you must also specifiy your mobile carrier');
                    document.getElementById('mobileCarrier').focus();
                    return;
                }
            }
        }


        if ($F('chkTosDate') == null || $F('chkTosDate') == '') {
            alert('You must read and agree to the Terms of Service.');
            $('chkTosDate').focus();
            return;
        }

        if ($F('chkPrivacyDate') == null || $F('chkPrivacyDate') == '') {
            alert('You must certify that you have read the Privacy Statement.');
            $('chkPrivacyDate').focus();
            return;
        }

        new Ajax.Request('Data/Extra_Save.ashx',
				{
				    parameters: $(document.forms[0].id).serialize(),
				    onSuccess: function(response) {



				        //document.location.href = 'AddEditExtra.aspx?z=' + response.responseText;
				        //document.location.href = 'Default.aspx';
				        // is the profile currently active?
				        var expireDate = $F('txtExpireDate');

				        //				        var bd = $F('txtBirthDate');
				        //				        var re = /^(0?[1-9]|[12][0-9]|3[01])\/(0?[1-9]|1[0-2])\/(19|20)\d{2}$/;
				        //				        if (!re.test(bd)) { alert('Birthday must be dd/mm/ccyy format'); return; }
				        //				        var sd = bd.split("/")
				        //				        var today = new Date();
				        //				        var birthday = new Date(sd[2], sd[1], sd[0]);
				        //				        var age = today - birthday;

				        var dt = new Date();

				        var _activate = true;


				        if (response.responseText.indexOf('&code=') > 0) {
				            document.location.href = "Default.aspx";
				        }
				        else {
				            if (response.responseText.length > 0)
				                document.location.href = "ActivateProfile.aspx?z=" + response.responseText + '&dt=' + escape(dt);
				        }

				        //				        if ((Math.floor(((age / 3600) / 24) / 365.25) >= 15) || (expireDate < today)) {

				        //				        }
				        //				        else {
				        //				            document.location.href = "Default.aspx";
				        //				        }



				    },

				    onFailure: function(response) {
				        var errors = '';
				        errors += (response.responseText) ? response.responseText : response;
				        alert(errors);
				    }
				});
    }
};