if (typeof(window['console']) == 'undefined') {
    console = { log: function() {} };
}
var owner_person = null;
var app_params = null;

/* {{{ request_params(method, postdata) */
function request_params(method, postdata) {
    var params = {};
    params[opensocial.ContentRequestParameters.AUTHENTICATION] = opensocial.ContentRequestParameters.AuthenticationType.NONE;
    if (method == 'post') {
        params[opensocial.ContentRequestParameters.METHOD] = opensocial.ContentRequestParameters.MethodType.POST;
        if (postdata) {
            params[opensocial.ContentRequestParameters.POST_DATA] = gadgets.io.encodeValues(postdata);
        }
    } else {
        params[opensocial.ContentRequestParameters.METHOD] = opensocial.ContentRequestParameters.MethodType.GET;
    }
    params[opensocial.ContentRequestParameters.CONTENT_TYPE] = opensocial.ContentRequestParameters.ContentType.HTML;

    return params;
}
/* }}} */

function redirect_top(url) {
    console.log(url);
    url = url.replace(new RegExp('http://' + HOSTNAME), '');
    var params_arr = new Array();
    params_arr.push("'path': '" + url + "'");
    var params = '{' + (params_arr.join(', ')) + '}';
    params = encodeURIComponent(params);
    url = 'http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=' + APP_ID + '&appParams=' + params; 
    console.log(url);

    window.top.location = url;
}

/* {{{ doMakeRequest(url) */
function doMakeRequest(url)
{
    var params = request_params();
    opensocial.makeRequest(url, gotMakeRequest, params);
}
/* }}} */

/* {{{ submit_form(id) */
function submit_form(id, action) {
    var form = $('#' + id);
    var postdata = {}
    $(':input', form).each(function() { postdata[this.name] = this.value; });
    var params = request_params('post', postdata);

    opensocial.makeRequest(action, gotMakeRequest, params);
}
/* }}} */

/* {{{ gotMakeRequest(response, url, errored) */
function gotMakeRequest(response, url, errored)
{
    var c = document.getElementById('mainwrap');
    if(!errored)
    {
        c.innerHTML = response;

        // init friend selectors
        $('.friend_selector_condensed').each(function(i) {
            fs = new FriendSelectorCondensed(this);
        });

        location.href = '#page_top';
    }
    else
    {
        c.appendChild(document.createTextNode("makeRequest failed:(" + response + ")(" + url + ")(" + errored + ")" + "\r\n"));
    }
}
/* }}} */

/* {{{ FriendSelectorCondensed class */
var FriendSelectorCondensed = function(elem) { this.init(elem); };
FriendSelectorCondensed.prototype = {
    /* {{{ init(elem) */
    init: function(elem) {
        this.elem = elem;
        this.checkboxes = new Array();
        this.invited_ids = new Array();
        this.load_friends();
    },
    /* }}} */

    /* {{{ load_friends() */
    load_friends: function() {
        // load friend ids, names, and pictures from opensocial
        var container = opensocial.Container.get();
        var data_request = container.newDataRequest();

        var friend_request = data_request.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS);
        data_request.add(friend_request);

        var that = this;
        data_request.send(function(data) {
            that.friends = data.get(opensocial.DataRequest.Group.VIEWER_FRIENDS).getData().asArray();
            that.draw();
            });
    },
    /* }}} */

    /* {{{ draw() */
    draw: function() {
        $(this.elem).css({overflow: 'auto', textAlign: 'center'});
        var tablediv = document.createElement('div');
        $(tablediv).css({overflow:'auto', marginBottom: '10px'}).height($(this.elem).height() - 40);
        this.elem.appendChild(tablediv);
        var table = document.createElement('table');
        tablediv.appendChild(table);
        var tbody = document.createElement('tbody');
        table.appendChild(tbody);
        this.tbody = tbody;
        
        var that = this;
        $.each(this.friends, function() {
            var row = document.createElement('tr');
            var td1 = document.createElement('td');
            var checkbox = document.createElement('input');
            checkbox.setAttribute('type', 'checkbox');
            checkbox.setAttribute('value', this.getField(opensocial.Person.Field.ID));
            that.checkboxes.push(checkbox);
            td1.appendChild(checkbox);

            var td2 = document.createElement('td');
            $(td2).css({textAlign: 'left'});
            var span = document.createElement('span');
            span.onclick = function(e) { checkbox.checked = !checkbox.checked; return false; }
            span.appendChild(document.createTextNode(
                this.getField(opensocial.Person.Field.NAME)));
            td2.appendChild(span);

            row.appendChild(td1);
            row.appendChild(td2);

            $(row).css({cursor: 'pointer'});
            
            that.tbody.appendChild(row);
        });

        var buttonsdiv = document.createElement('div');
    
        var button = document.createElement('button');
        button.appendChild(document.createTextNode(this.get_button_text()));
        button.onclick = function() {
            console.log('clicked on the button d00d');
            that.request_sends();
        }

        buttonsdiv.appendChild(button);
        buttonsdiv.appendChild(document.createElement('br'));

        if ($(this.elem).attr('withskip') == 'true') {
            skip = document.createElement('a');
            skip.appendChild(document.createTextNode('skip'));
            skip.href = '#';
            var action = $(this.elem).attr('action');
            $(skip).addClass('button_link').css({marginLeft: '10px'}).click(
                function(e) { doMakeRequest(action); return false; });
            buttonsdiv.appendChild(skip);
        }

        this.elem.appendChild(buttonsdiv);

        // adjust height
        $(this.elem).height(this.elem.scrollHeight);
        $(this.elem).height($(this.elem).height()+40);
    },
    /* }}} */

    /* {{{ get_button_text() */
    get_button_text: function() {
        var type = $(this.elem).attr('type');
        var invite = $(this.elem).attr('invite');
        var text = 'Send ';
        if (type) {
            // @todo if it starts with 'send', cut that off.
            text += type;
        }
        if (invite == 'true') {
            text += ' Invite';
        } else {
            text += ' Request';
        }

        return text;
    },
    /* }}} */

    /* {{{ request_sends() */
    request_sends: function() {
        this.request_one(0);
    },
    /* }}} */

    /* {{{ request_one(i) */
    request_one: function(i) {
        var checkbox = this.checkboxes[i];
        var that = this;
        if (checkbox) {
            if (checkbox.checked) {
                message = opensocial.newMessage($(this.elem).attr('content'));
                opensocial.requestShareApp(checkbox.value, message, function(sent) {
                    if (sent) {
                        that.invited_ids.push(checkbox.value);
                        // @todo make an ajax call to let us know the request was sent?
                    }
                    checkbox.checked = false;
                    that.request_one(i + 1);
                });
            } else {
                that.request_one(i + 1);
            }
        } else {
            this.redirect();
        }
    },
    /* }}} */

    /* {{{ redirect() */
    redirect: function() {
        var action = $(this.elem).attr('action');
        if (action) {
            var postdata = {ids: this.invited_ids.join(",")}
            var params = request_params('post', postdata);
            opensocial.makeRequest(action, gotMakeRequest, params);
        }
    }
    /* }}} */
};
/* }}} */

/* {{{ FriendSelector class */
/*
var FriendSelector = function(elem) { this.init(elem); };
FriendSelector.prototype = FriendSelectorCondensed.prototype;
FriendSelector.prototype.draw = function() {
        console.log('this.friends:');
        console.log(this.friends);
        var that = this;
        $.each(this.friends, function() {
            var box = document.createElement('div');
            $(box).width(100).height(100).css(
                {float: 'left', textAlign: 'center', marginBottom: '10px',
                 cursor: 'pointer', backgroundColor: '#ffffff'});

            var thumbdiv = document.createElement('div');
            $(thumbdiv).height(70).css({overflow: 'hidden'});
            var thumb = document.createElement('img');
            thumb.setAttribute('src', this.getField(opensocial.Person.Field.THUMBNAIL_URL));
            thumbdiv.appendChild(thumb);
            box.appendChild(thumbdiv);

            //box.appendChild(document.createElement('br'));

            box.appendChild(document.createTextNode(
                this.getField(opensocial.Person.Field.NAME)
            ));
            var id = this.getField('id');
            box.onclick = function(e) { console.log(e); console.log('box clicked, id is ' + id); };
            that.elem.appendChild(box);
        });
};
*/
/* }}} */

function post_bulletin(subject, body) {
    var os_token = MyOpenSpace.MySpaceContainer.OSToken;
    var container = opensocial.Container.get();
    //var supported_targets = container.getMySpaceEnvironment().getSupportedPostToTargets();
    // @todo make sure that BULLETINS is supported; if not, try another target
    var target = 'BULLETINS';

    var message = opensocial.newMessage(body);
    message.setField(opensocial.Message.Field.TITLE, subject);
    message.setField(opensocial.Message.Field.TYPE, target);
    container.postTo(os_token, message, owner_person);
}

function bulletin_body(id, quiz_id, quiz_app_id) {
    var body = document.getElementById(id).innerHTML;
    body += '<div style="font-size:18px;text-align:center;">';
    quiz_app_id = CENTRAL_APP_ID; // @todo change this back once single quizzes work

    var params_arr = new Array();
    params_arr.push("'app_id': '" + quiz_id + "'");
    params = "{" + (params_arr.join(', ')) + "}";
    params = encodeURIComponent(params);
    body += '<a href="http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=' + quiz_app_id + '&appParams=' + params + '">Take This Quiz</a><br><br>';

    params_arr.push("'path': '/'");
    params = "{" + (params_arr.join(', ')) + "}";
    params = encodeURIComponent(params);
    body += '<a href="http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=' + CENTRAL_APP_ID + '&appParams=' + params + '">See More Quizzes</a>';

    body += '</div>';
    return body;
}

function unhide_question_entry(max_questions) {
    done = false;
    n = 0;
    while (!done && n < max_questions) {
        questions_div = $('#quiz_question_' + n);
        if (questions_div.hasClass('hidden')) {
            questions_div.removeClass('hidden');
            done = true;
        }
        ++n;
        if (n == max_questions) {
            $('#add_question').addClass('hidden');
        }
    }
}

function unhide_result_entry(max_results) {
    done = false;
    n = 0;
    while (!done && n < max_results) {
        results_div = $('#quiz_result_' + n);
        if (results_div.hasClass('hidden')) {
            results_div.removeClass('hidden');
            done = true;
        }
        ++n;
        if (n == max_results) {
            $('#add_result').addClass('hidden');
        }
    }
}

/* {{{ init() */
function init() {
    console.log('init called');

    app_params = opensocial.getEnvironment().getParams();

    // fetch the user id
    var personId = opensocial.DataRequest.PersonId.OWNER;
    var dr = opensocial.newDataRequest();
    var opt_params = {};
    var personReq = dr.newFetchPersonRequest(personId);
    dr.add(personReq,'SmallPerson');
    dr.send(finish);
}
/* }}} */

/* {{{ finish(data) */
function finish(data) {
    console.log('finish called');
    owner_person = data.get('SmallPerson').getData();
    if (!owner_person) {
        console.log('no person');
        // @todo - this means they haven't added the app yet.
    } else {
        var user_id = owner_person.getField('id');
        console.log('got person: ' + user_id);

        var app_id = APP_ID;
        if (app_params['app_id']) {
            app_id = app_params['app_id'];
        }

        var path = BASE_PATH;
        if (app_params['path']) {
            path = app_params['path'];
        }
        if (path[0] != '/') {
            path = '/' + path;
        }

        var url = "http://" + HOSTNAME + path;
        doMakeRequest(url);
    }
}
/* }}} */

/* {{{ profile_init() */
function profile_init() {
    console.log('init called');

    app_params = opensocial.getEnvironment().getParams();

    // fetch the user id
    var personId = opensocial.DataRequest.PersonId.OWNER;
    var dr = opensocial.newDataRequest();
    var opt_params = {};
    var personReq = dr.newFetchPersonRequest(personId);
    dr.add(personReq,'SmallPerson');
    dr.send(profile_finish);
}
/* }}} */

/* {{{ profile_finish(data) */
function profile_finish(data) {
    owner_person = data.get('SmallPerson').getData();
    if (!owner_person) {
        console.log('no person');
        // @todo - this means they haven't added the app yet.
    } else {
        var user_id = owner_person.getField('id');
        console.log('got person: ' + user_id);

        var app_id = APP_ID;
        if (app_params['app_id']) {
            app_id = app_params['app_id'];
        }

        var path = BASE_PATH;
        if (app_params['path']) {
            path = app_params['path'];
        }
        if (path[0] != '/') {
            path = '/' + path;
        }

        var url = "http://" + HOSTNAME + '/central_profile';
        doMakeRequest(url);
    }
}
/* }}} */

/* {{{ home_init() */
function home_init() {
    console.log('init called');

    app_params = opensocial.getEnvironment().getParams();

    // fetch the user id
    var personId = opensocial.DataRequest.PersonId.OWNER;
    var dr = opensocial.newDataRequest();
    var opt_params = {};
    var personReq = dr.newFetchPersonRequest(personId);
    dr.add(personReq,'SmallPerson');
    dr.send(home_finish);
}
/* }}} */

/* {{{ home_finish(data) */
function home_finish(data) {
    owner_person = data.get('SmallPerson').getData();
    if (!owner_person) {
        console.log('no person');
        // @todo - this means they haven't added the app yet.
    } else {
        var user_id = owner_person.getField('id');
        console.log('got person: ' + user_id);

        var app_id = APP_ID;
        if (app_params['app_id']) {
            app_id = app_params['app_id'];
        }

        var path = BASE_PATH;
        if (app_params['path']) {
            path = app_params['path'];
        }
        if (path[0] != '/') {
            path = '/' + path;
        }

        var url = "http://" + HOSTNAME + '/central_home';
        doMakeRequest(url);
    }
}
/* }}} */
