/*******************
 * MyPIN integration
 *
 */

$.MyPIN = {
    setup: function() {

        this.log("mypin setup");
        //this.log($.cookies());
        $.MyPIN.User = false;
        $.MyPIN.RememberMe = false;
        $.MyPIN.Version = 1;
        $.each($.cookies(), function(key,val) {
            if (key.match(/^auth_tkt_mypin_/)) {
                $.MyPIN.User = $.MyPIN.unpackAuthTkt($.cookie(key));
            }
            if (key.match(/^mypin2_auth_tkt/)) {
                $.MyPIN.Version = 2;
                $.MyPIN.User = $.MyPIN.unpackAuthTkt($.cookie(key));
            }
            if (key == 'source_data') {
                $.MyPIN.RememberMe = $.parseJSON(Base64.smartDecode($.cookie(key)));
            }
            if (key == 'mypin2_remember_me') {
                $.MyPIN.Version = 2;
                var rm = $.parseJSON(Base64.smartDecode($.cookie(key)));
                // mangle to match version 1 struct
                var verOne = {firstName:rm.first_name,lastName:rm.last_name,email:rm.email};
                $.MyPIN.RememberMe = verOne;
            }
        });
        this.log("user:", this.User);
        this.log("rememberMe:", this.RememberMe);

        // insert element after <body> and before <container>
        // that contains the mypin header/logo/welcome msg
        $.MyPIN.setHeader();
        $.MyPIN.fillInForm();

    }
};

$.MyPIN.unpackAuthTkt = function(str) {
    var decoded = Base64.smartDecode(str);
    //this.log('decoded', decoded);
    var clean = decoded.replace(/^"|"$/, decoded);
    //this.log('clean', clean);
    if (clean.length < 40) {
        throw new Exception("tkt too short");
    }
    var matches = clean.match(/^(.{32})(.{8})(.+?)!(.*)$/);
    //this.log(matches);
    var user;
    if (this.Version == 2) {
        var payload = $.parseJSON(Base64.smartDecode(matches[4]));
        // mangle to match version 1 struct
        var verOne = {first_name:payload.first_name, last_name:payload.last_name, email:{emailAddress:payload.email}};
        verOne.address = {city:payload.city,state:payload.state,countryCode:payload.cntry,zipCode:payload.postal};
        verOne.phone = {phoneNumber:payload.phone};
        user = { uid: matches[3], payload: verOne };
    }
    else {
        user = { uid: matches[3], payload: $.parseJSON(matches[4]) };
    }
    return user;
}

$.MyPIN.fillInForm = function() {

    if (this.User) {
        if ($('#ctb_first_name')) {
            $('#ctb_first_name').val(this.User.payload.first_name);
        }
        if ($('#ctb_last_name')) {
            $('#ctb_last_name').val(this.User.payload.last_name);
        }
        if ($('#ctb_email')) {
            $('#ctb_email').val(this.User.payload.email.emailAddress);
        }
        if ($('#ctb_city')) {
            $('#ctb_city').val(this.User.payload.address.city);
        }
        if ($('#ctb_zipcode')) {
            $('#ctb_zipcode').val(this.User.payload.address.zipCode);
        }
        if ($('#ctb_phone')) {
            $('#ctb_phone').val(this.User.payload.phone.phoneNumber);
        }
        if ($('#ctb_cntry_code')) {
            $('#ctb_cntry_code').val(this.User.payload.address.countryCode);
        }
        if ($('#ctb_st_code')) {
            $('#ctb_st_code').val(this.User.payload.address.state);
        }
    }
    else if (this.RememberMe) {
        if ($('#ctb_first_name')) {
            $('#ctb_first_name').val(this.RememberMe.firstName);
        }       
        if ($('#ctb_last_name')) {
            $('#ctb_last_name').val(this.RememberMe.lastName);
        }       
        if ($('#ctb_email')) {
            $('#ctb_email').val(this.RememberMe.email);
        }
    }
}

$.MyPIN.setHeader = function() {
    var html = '' +
       '<div id="mypin-header"><div id="mypin-header-wrapper">' +
        '<div id="mypin-logo">' +
         '<a href="'+this.URL+'/">' +
         '<img src="'+this.URL+'/static/img/pin.png" alt="Public Insight Network" id="logo" />' +
         '</a>' +
        '</div>';

    // if logged in to MyPIN, display name and Logout links
    if (this.User) { 
        html += '<div id="mypin-buttons">' +
         'Welcome, <a href="'+this.URL+'/home">' + this.User.payload.first_name + '</a>' +
         ' | <a href="'+this.URL+'/logout?back='+window.location+'">Logout</a>' +
        '</div>';
    }

    // not logged in, but has an account
    else if (this.RememberMe) {
        var name = this.RememberMe.firstName + ' ' + this.RememberMe.lastName;
        html += '<div id="mypin-buttons">' +
         'Welcome back, <a href="'+this.URL+'/home">' + name + '</a>.' +
         ' (<a href="'+this.URL+'/logout?remember_me=clear&amp;back='+window.location+'">Not ' + name + '?</a>)' +
        '</div>'; 
    }

    // no MyPIN acccount
    else {
        html += '<div id="mypin-buttons">' +
         '<a href="'+this.URL+'/?show_login=1&amp;back='+window.location+'" id="login-button">Login</a>' +
         '<a href="'+this.URL+'/signup" id="create-account-button" title="Sign up">Create Account <span>&rsaquo;</span></a>' +
        '</div>';
    }

    html += '</div></div>'; // close

    $(html).prependTo($('body'));

}

if (typeof console != 'undefined') {
    if (window.console && !console.debug) {
        // safari
        //alert("window.console is defined");
        $.MyPIN.log = function() { window.console.log(arguments[0]) };
    }
    else if (console.debug) {
        // firebug
        $.MyPIN.log = function() { console.log.apply( console, arguments ) };
    }
    else {
        //alert("no window.console or console.debug");
        $.MyPIN.log = function() { }; // no-op
    }
}
else {
    $.MyPIN.log = function() {}; // no-op
}

