var IE = document.all? true:false;

var challenge = {};
var app = {};
var facebook = {};

challenge = {
    currentQuestion : 0,
    friendId: 0,
    questionId: 0,
    
    wallData : {},
    setWallData: function (wallData) {
        this.wallData = wallData
    },

    setQuestion : function (friendId, questionId) {
        this.currentQuestion++;
        this.friendId = friendId;
        this.questionId = questionId;;
    },

    answer: function (value)  {
        checkAnawerUrl = 'quizz/answer'; 
        app.showLoading();

        if ($('#publish-feed:checked').length) {
//            $.ajax({
//                url:  app.preparePageUrl('quizz/wallPost'),
//                success: function (response) {
//                    app.loadPageCallback(response);
//                },
//                data: {
//                    friend_user_id: challenge.friendId,
//                    question_id: challenge.questionId,
//                    answer_result: value,
//                    question: $('#question  > .quesion-title').html()
//                },
//                dataType: 'json',
//                type: 'POST'
//            })
            
            var msg = {
                to: challenge.friendId,
                name: challenge.wallData.name,
                caption: challenge.wallData.caption,
                href: challenge.wallData.href,
                //picture: appUrl + '/assets/img/logo.png',
                actions : challenge.wallData.actions,
                properties : challenge.wallData.properties
            }
       
            facebook.publishStream(msg, null);
        }

        $.ajax({
            url:  app.preparePageUrl('quizz/answer'),
            success: function (response) {
                app.loadPageCallback(response);
            },
            data: {
                friend_user_id: challenge.friendId,
                question_id: challenge.questionId,
                answer_result: value,
                publish: $('#publish-feed:checked').length==1
            },

            complete: function() {
                app.scrollToTop();
                app.stopLoading();
                FB.XFBML.parse();
                app.consoleInfo('loadPage(): Completed request');
            },
            dataType: 'json',
            type: 'POST'
        })

    },

    nextQuestion : function () {
        return app.loadPage('quizz/index');
    },

    unlockAnswer: function (answerId) {
        $.ajax({
            cache: false,
            url: app.preparePageUrl('quizz/unlock/' + answerId),
            beforeSend: function() {
                app.showLoading();
            },
            success: function(data) {
                if (data.error) {
                    
                }
                app.loadPageCallback(data);
            },
            complete: function() {
                app.scrollToTop();
                app.stopLoading();
                FB.XFBML.parse();
            },
            dateType: 'json'
        });
    }
}

app = {
    consoleInfo : function (str) {
        if (!IE && $('#debug') && window.console) {
            console.info(str);
        }
    },

    scrollToTop : function () {
    },

    saveQuestion: function (questionId) {
        $.ajax({
            cache: false,
            url: app.preparePageUrl('admin/question/save/', false),
            beforeSend: function() {
                app.showLoading();
            },
            success: function(data) {
                if (!data.error) {
                    alert('Question is saved');
                } else {
                    alert('Error when saving question')
                }
                app.stopLoading();
            },
            dateType: 'json',
            data : {
                'id': questionId,
                'question': $('#question-text-' + questionId).val()
            },
            type: 'POST'
        })
    },

    deleteQuestion: function (questionId) {
        $.ajax({
            cache: false,
            url: app.preparePageUrl('admin/question/delete/', false),
            beforeSend: function() {
                app.showLoading();
            },
            success: function(data) {
                if (!data.error) {
                    alert('Question& related data are removed');
                } else {
                    alert('Error when deleting question')
                }
                $('#question-item-' + questionId).remove();
                app.stopLoading();
            },
            dateType: 'json',
            data : {
                'id': questionId
            },
            type: 'POST'
        })
    },

    adjustHeight : function (height) {
    //        FB.Arbiter.inform('setSize', {
    //            height: 3000
    //        });
    },

    stopLoading : function () {
        $('#axcoto-loading-overlay').hide();
    },

    showLoading : function () {
        $('#axcoto-loading-overlay').show();
    },

    /**
     * Prepare a PAGE URL to reload whole of page via Ajax
     */
    preparePageUrl: function (url, noAjaxLoad) {
        if (url.indexOf(appUrl) == -1) {
            url = appUrl + url;
        }

        if (url.indexOf('?') == -1) {
            url += '?';
        } else {
            url += '&';
        }
        url += fb_sig_params;

        if (typeof noAjaxLoad == 'undefined') {
            url +=  '&_load_page_by_ajax=true';
        }

        url +=  '&rand='+Math.floor(Math.random()*10000);
        return url;
    },

    /**
     * Make sure we parse javascript code which returned
     */
    loadPageCallback: function (response) {
        if (!response.data) {
            this.consoleInfo("loadPageCallback(): Did not receive any data in the response");
            this.stopLoading();
        } else {
            this.consoleInfo('loadPageCallback(): Received a valid response.');
            processAjax(response.data);
            // eval javascript in ajax html
            $('#context-panel script[type!="text/fbml"]').each(function(index) {
                var js = $(this).html();
                jQuery.globalEval(js);
            });
            this.stopLoading();
        }
    },

    /**
     * Load whole page via xmlHttpRequest! We reload WHOLE page (most of code between <body></body>)
     */
    loadPage : function (page, cb) {
        this.consoleInfo('loadPage(): '+page+' ...');

        page = this.preparePageUrl(page);
        this.consoleInfo('page=' + page);

        $.ajax({
            cache: false,
            url: page,
            beforeSend: function() {
                app.showLoading();
            },
            success: function(data) {
                app.consoleInfo('loadPage(): Success, executing callback');
                app.loadPageCallback(data);
            },
            complete: function() {
                app.scrollToTop();
                app.stopLoading();
                FB.XFBML.parse();
                if (cb) {
                    cb();
                }
                app.consoleInfo('loadPage(): Completed request');
            },
            dateType: 'json'
        });
    },

    loadPageNoCallback : function (page) {
        page = this.preparePageUrl(page);
        this.consoleInfo('loadPageNoCallback(): '+page);
        $.ajax({
            cache: false,
            url: page,
            success: function(data) {
                app.consoleInfo('loadPageNoCallback(): Success, executing callback');
            },
            complete: function() {
                app.consoleInfo('loadPageNoCallback(): Completed request');
            }
        });
    }
}

facebook = {
    removeDialog: function () {
        $('#fb-root  .fb_dialog').hide();
    },

    publishStream : function (param, cb) {
        FB.ui({
            method: 'feed',
            display: 'iframe',
            caption: param.caption,
            name: param.name,
            link: appCanvas + 'quizz/result',
            message: 'Hola! He respondido unas preguntas muy divertidas sobre ti... Te invito a ver lo que he respondido!',
            to: param.to,
            redirect_uri: app.preparePageUrl('quizz/publishPostBack/'),
            //picture: param.picture,
            properties : param.properties,
            actions : param.actions,
            next: null
        });
    }
}













function processAjax(content) {
    //$('#context-panel').html(content);
    if (nonIE) {
        $('#context-panel').html(content);
        return true;
    }
    //alert('ie');
    var
    spanned = content,
    html5els = ['nav','section', 'header','article','footer'], //etc...
    attributes = ['id', 'class']; //etc...

    $.each(html5els, function (index, tag) {
        var re = new RegExp('<(\/?)'+tag+'([^>]*)>', 'g');
        spanned = spanned.replace(re, '<$1span htmlfix="'+tag+'"$2>');
    })
    
    $('#context-panel').html(spanned);

    var fixNode = function (index, tag) {
        tag = $(tag);
        var node = $('<' +tag.attr('htmlfix') + '/>')
        $.each(attributes, function (indexAttb, attb) {
            node.attr(attb, tag.attr(attb));
        })
        node.html(tag.html());
        tag.replaceWith(node);
    }

    $('span[htmlfix|="nav"]', '#context-panel').each(function (indexSpan, tag) {
        fixNode(indexSpan, tag)
    });
    $('span[htmlfix|="section"]', '#context-panel').each(function (indexSpan, tag) {
        fixNode(indexSpan, tag)
    });
    $('span[htmlfix|="header"]', '#context-panel').each(function (indexSpan, tag) {
        fixNode(indexSpan, tag)
    });
    $('span[htmlfix|="footer"]', '#context-panel').each(function (indexSpan, tag) {
        fixNode(indexSpan, tag)
    });
    $('span[htmlfix|="article"]', '#context-panel').each(function (indexSpan, tag) {
        fixNode(indexSpan, tag)
    });
    
    return true;
}

