// JavaScript Document

var ikon_communicating = '<img src="/images/loader_minitext.gif">';

function update_page_with_game_results(quiz_round_ident) {
    document.getElementById('quiz_round_ident').value = quiz_round_ident;

    new Ajax.Request(base_url + "/mq_ws.pl", {
      postBody: "<Quiz><RequestCorrection><QuizRoundIdent>" + quiz_round_ident + "</QuizRoundIdent></RequestCorrection></Quiz>",
      onSuccess: function(transport) {
        $("game_result").innerHTML = transport.responseText;
        facebookGamePlayed(quiz_round_ident);
        get_toplist('friends', 1);
      },
      onFailure: function(transport) {
          alert('failure base ' + transport.status);
      }
    });

    get_toplist('', 1);
}

function facebookGamePlayed(quiz_round_ident) {
    if (!$('facebookHeadTag')) {
        return;
    }

    var app_name = document.getElementById('facebookAppName');
    var url = base_url + '/fb/' + (app_name ? app_name.value : 'royalquiz') + '/find_member_quiz/game_played/' + quiz_round_ident;

    new Ajax.Request(url, {
      method: 'get',
      onSuccess: function(transport) {
        $('user_result_points').value = transport.responseJSON.user_result_points;

        // STREAM POST
        var points          = transport.responseJSON.user_result_points;
        var correct_answers = transport.responseJSON.user_result_correct_answers;
        var total_questions = transport.responseJSON.game_total_questions;

        var caption = '';
        if (points > 0) {
            caption = $('js_text_fb_caption').value;
            caption = caption.replace('POINTS', points);
            caption = caption.replace('CORRECT_ANSWERS', correct_answers);
            caption = caption.replace('TOTAL_QUESTIONS', total_questions);
        }

        var category_name;
        if (fb_stream_publish_properties.Category) {
            category_name = fb_stream_publish_properties.Category.text;
        }
        if (fb_stream_publish_properties.Kategori) {
            category_name = fb_stream_publish_properties.Kategori.text;
        }
        category_name = category_name.replace(/&aring;/g,'å').replace(/&auml;/g,'ä').replace(/&ouml;/g,'ö');
        category_name = category_name.replace(/&Aring;/g,'Å').replace(/&Auml;/g,'Ä').replace(/&Ouml;/g,'Ö');
        category_name = category_name.replace(/&amp;/g,'&');
        if (fb_stream_publish_properties.Category) {
            fb_stream_publish_properties.Category.text = category_name;
        }
        if (fb_stream_publish_properties.Kategori) {
            fb_stream_publish_properties.Kategori.text = category_name;
        }

        var attachment = {
            'name':        $('js_text_quiz_name').value,
            'href':        $('js_text_quiz_url_top').value,
            'caption':     caption,
            'description': $('js_text_description').value,
            'properties' : fb_stream_publish_properties
        };
        if ($('js_text_description_image_url').value) {
            attachment.media = [{'type':'image','src':$('js_text_description_image_url').value, 'href':$('js_text_quiz_url_top').value}];
        }
// console.log(attachment);
        var actionLinks = [{ "text": $('js_text_fb_action_link_text').value, "href": $('js_text_quiz_url_top').value}];
        FB.Connect.streamPublish('',attachment,actionLinks,null,$('js_text_fb_user_message_prompt').value);
      }
    });
}

function publishedShowFBSharer() {
    // STREAM POST
    var attachment = {
        'name':        $('js_text_quiz_name').value,
        'href':        $('js_text_quiz_url_top').value,
        'caption':     $('js_text_fb_caption').value,
        'description': $('js_text_description').value,
        'properties' : fb_stream_publish_properties
    };
    if ($('js_text_description_image_url').value) {
        attachment.media = [{'type':'image','src':$('js_text_description_image_url').value, 'href':$('js_text_quiz_url_top').value}];
    }
    var actionLinks = [{ "text": $('js_text_fb_action_link_text').value, "href": $('js_text_quiz_url_top').value}];
    FB.Connect.streamPublish('',attachment,actionLinks,null,$('js_text_fb_user_message_prompt').value);
}

function set_rating(rating) {
    var quiz_round_ident   = document.getElementById('quiz_round_ident').value;
    var rating_exclamation = document.getElementById('rating_exclamation');

    var http = getHTTPObject();
    if (http) {
        http.open(
            "POST",
            base_url + "/mq_ws.pl",
            true);

        http.onreadystatechange = function() {
            if (http.readyState == 4) {
                var re = /^<Quiz><error/;
                if (re.test(http.responseText)) {
                    // handle error ?
                } else {
                    $("rating_actions").innerHTML = http.responseText;
                    if (rating_exclamation) {
                        rating_exclamation.style.display = 'none';
                    }
                    get_rating_graphical();
                }
            } else {
                $("rating_actions").innerHTML = ikon_communicating;
            }
        }

        http.send("<Quiz><SetRating><QuizRoundIdent>" + quiz_round_ident + "</QuizRoundIdent><Rating>" + rating + "</Rating></SetRating></Quiz>");
    }
}

function get_rating_graphical() {
    var quiz_ident = document.getElementById('quiz_ident').value;

    var http = getHTTPObject();
    if (http) {
        http.open(
            "POST",
            base_url + "/mq_ws.pl",
            true);

        http.onreadystatechange = function() {
            if (http.readyState == 4) {
                var re = /^<Quiz><error/;
                if (re.test(http.responseText)) {
                    // handle error ?
                } else {
                    document.getElementById("rating_graphical").innerHTML = http.responseText;
                }
            } else {
                document.getElementById("rating_graphical").innerHTML = ikon_communicating;
            }
        }

        http.send("<Quiz><GetRatingGraphical><QuizIdent>" + quiz_ident + "</QuizIdent></GetRatingGraphical></Quiz>");
    }
}

function set_admin_rating(rating) {
    var feedback_container = document.getElementById('admin_rating_feedback');
    var quiz_ident         = document.getElementById('quiz_ident').value;

    var http = getHTTPObject();
    if (http && feedback_container) {
        http.open(
            "POST",
            base_url + "/mq_ws.pl",
            true);

        http.onreadystatechange = function() {
            if (http.readyState == 4) {
                var re = /^<Quiz><error/;
                if (re.test(http.responseText)) {
                    // handle error ?
                } else {
                    feedback_container.innerHTML = http.responseText;
                }
            } else {
                feedback_container.innerHTML = ikon_communicating;
            }
        }

        http.send("<Quiz><SetAdminRating><QuizIdent>" + quiz_ident + "</QuizIdent><Rating>" + rating + "</Rating></SetAdminRating></Quiz>");
    }
}

function set_admin_locale(locale) {
    var feedback_container = document.getElementById('admin_rating_feedback');
    var quiz_ident         = document.getElementById('quiz_ident').value;

    var http = getHTTPObject();
    if (http && feedback_container) {
        http.open(
            "POST",
            base_url + "/mq_ws.pl",
            true);

        http.onreadystatechange = function() {
            if (http.readyState == 4) {
                var re = /^<Quiz><error/;
                if (re.test(http.responseText)) {
                    // handle error ?
                } else {
                    feedback_container.innerHTML = http.responseText;
                }
            } else {
                feedback_container.innerHTML = ikon_communicating;
            }
        }

        http.send("<Quiz><SetAdminLocale><QuizIdent>" + quiz_ident + "</QuizIdent><Locale>" + locale + "</Locale></SetAdminLocale></Quiz>");
    }
}

function admin_set_private() {
    var feedback_container = document.getElementById('admin_rating_feedback');
    var quiz_ident         = document.getElementById('quiz_ident').value;

    var http = getHTTPObject();
    if (http && feedback_container) {
        http.open(
            "POST",
            base_url + "/mq_ws.pl",
            true);

        http.onreadystatechange = function() {
            if (http.readyState == 4) {
                var re = /^<Quiz><error/;
                if (re.test(http.responseText)) {
                    // handle error ?
                } else {
                    feedback_container.innerHTML = http.responseText;
                }
            } else {
                feedback_container.innerHTML = ikon_communicating;
            }
        }

        http.send("<Quiz><AdminSetPrivate><QuizIdent>" + quiz_ident + "</QuizIdent></AdminSetPrivate></Quiz>");
    }
}

function admin_unpublish() {
    var feedback_container = document.getElementById('admin_rating_feedback');
    var quiz_ident         = document.getElementById('quiz_ident').value;

    var http = getHTTPObject();
    if (http && feedback_container) {
        http.open(
            "POST",
            base_url + "/mq_ws.pl",
            true);

        http.onreadystatechange = function() {
            if (http.readyState == 4) {
                var re = /^<Quiz><error/;
                if (re.test(http.responseText)) {
                    // handle error ?
                } else {
                    feedback_container.innerHTML = http.responseText;
                }
            } else {
                feedback_container.innerHTML = ikon_communicating;
            }
        }

        http.send("<Quiz><AdminUnpublish><QuizIdent>" + quiz_ident + "</QuizIdent></AdminUnpublish></Quiz>");
    }
}

function mq_switch_toplist(type) {
    var all     = $('mq_toplist_all');
    var friends = $('mq_toplist_friends');

    all.style.display     = type == 'friends' ? 'none' : 'block';
    friends.style.display = type == 'friends' ? 'block' : 'none';

    var mq_toplist_tab_all     = $('mq_toplist_tab_all');
    var mq_toplist_tab_friends = $('mq_toplist_tab_friends');

    mq_toplist_tab_all.className     = type == 'friends' ? '' : 'active';
    mq_toplist_tab_friends.className = type == 'friends' ? 'active' : '';
}

function get_toplist(type, page) {
    var quiz_ident = $('quiz_ident').value;

    new Ajax.Request(base_url + "/mq_ws.pl", {
      postBody: "<Quiz><GetQuizToplistHTML><QuizIdent>" + quiz_ident + "</QuizIdent><Page>" + page + "</Page><Type>" + type + "</Type></GetQuizToplistHTML></Quiz>",
      onSuccess: function(transport) {
        var toplist = (type == 'friends') ? $('toplistfriends') : $('toplist');
        toplist.parentNode.innerHTML = transport.responseText;
      }
    });
}

function get_toplist_your_score() {
    var quiz_ident = document.getElementById('quiz_ident').value;

    new Ajax.Request(base_url + "/mq_ws.pl", {
      postBody: "<Quiz><GetQuizToplistHTMLCenteredAroundUser><QuizIdent>" + quiz_ident + "</QuizIdent></GetQuizToplistHTMLCenteredAroundUser></Quiz>",
      onSuccess: function(transport) {
        var toplist    = document.getElementById('toplist');
        toplist.parentNode.innerHTML = transport.responseText;
      }
    });
}

function get_login_form() {
    var http = getHTTPObject();
    if (http) {
        http.open(
            "POST",
            base_url + "/mq_ws.pl",
            true);

        http.onreadystatechange = function() {
            if (http.readyState == 4) {
                var re = /^<Quiz><error/;
                if (re.test(http.responseText)) {
                    // handle error ?
                } else {
                    document.getElementById("comment_actions").innerHTML = http.responseText;
                }
            } else {
                document.getElementById("comment_actions").innerHTML = ikon_communicating;
            }
        }

        http.send("<Quiz><GetLoginForm></GetLoginForm></Quiz>");
    }
}

function do_login() {
    var quiz_round_ident = document.getElementById('quiz_round_ident').value;
    var username         = document.getElementById('username').value;
    var password         = document.getElementById('password').value;

    if (comment == '') {
        document.getElementById("comment_actions").innerHTML = 'Skriv din kommentar i fältet ovan.';
        return;
    }

    var http             = getHTTPObject();
    if (http) {
        http.open(
            "POST",
            base_url + "/mq_ws.pl",
            true);

        http.onreadystatechange = function() {
            if (http.readyState == 4) {
                var re = /^<Quiz><error/;
                if (re.test(http.responseText)) {
                    // handle error ?
                } else {
                    // set cookie (?)
                    var error = http.responseText;
                    if (error) {
                        document.getElementById("comment_actions").innerHTML = error;
                    } else {
                        add_comment();
                    }
                }
            } else {
                document.getElementById("comment_actions").innerHTML = ikon_communicating;
            }
        }

        http.send("<Quiz><RequestUserLogin><QuizRoundIdent>" + quiz_round_ident + "</QuizRoundIdent><UserCredentials><Username>" + username + "</Username><Password>" + password + "</Password></UserCredentials><Format>html</Format></RequestUserLogin></Quiz>");
    }
}

var create_submitted = 0;

function submit_create(next_action) {
    if (create_submitted == 0) {
        document.getElementById('next_action').value = next_action;
        document.getElementById('parent_form').submit();
    }
    create_submitted = 1;
}

function write_question_delete_image() {
    var question_id = document.getElementById('question_id').value;

    var http = getHTTPObject();
    if (http) {
        http.open(
            "POST",
            base_url + "/mq_ws.pl",
            true);

        http.onreadystatechange = function() {
            if (http.readyState == 4) {
                var re = /^<Quiz><error/;
                if (re.test(http.responseText)) {
                    // handle error ?
                } else {
                    var error = http.responseText;
                    if (error) {
                        document.getElementById("delete_image").innerHTML = error;
                    } else {
                        document.getElementById('current_question_image').style.display = 'none';
                        document.getElementById('delete_image').style.display = 'none';
                    }
                }
            } else {
                document.getElementById("delete_image").innerHTML = ikon_communicating;
            }
        }

        http.send("<Quiz><DeleteQuestionImage><QuestionId>" + question_id + "</QuestionId></DeleteQuestionImage></Quiz>");
    }
}

function define_premium_set_preview_with_existing (background_url,background_image_id, header_background_color_top,header_background_color_bottom, ad_image_url,ad_image_width,ad_image_height,ad_image_id, footer_background_color_top,footer_background_color_bottom, accent_color, ad_url, ad_target) {
    define_premium_preview_set_background(background_url, background_image_id);
    define_premium_preview_set_header_background_color_top(header_background_color_top);
    define_premium_preview_set_header_background_color_bottom(header_background_color_bottom);
    define_premium_preview_set_ad(ad_image_url, ad_image_width, ad_image_height, ad_image_id, ad_url, ad_target);
    define_premium_preview_set_footer_background_color_top(footer_background_color_top);
    define_premium_preview_set_footer_background_color_bottom(footer_background_color_bottom);
    define_premium_preview_set_accent_color(accent_color);
}

function define_premium_preview_set_background(background_url,background_image_id) {
    document.getElementById('preview_background_container').style.backgroundImage = 'url(' + background_url + ')';
    document.getElementById('background_image_id').value = background_image_id;
}
function define_premium_preview_set_header_background_color_top(color) {
    if (is_color(color)) {
        document.getElementById('preview_header_top_container').style.backgroundColor = color;
        document.getElementById('header_background_color_top').value                  = color;
        hide('error_header_background_color_top');
    } else {
        document.getElementById('preview_header_top_container').style.backgroundColor = '';
        show('error_header_background_color_top');
    }
}
function define_premium_preview_set_header_background_color_bottom(color) {
    if (is_color(color) && document.getElementById('preview_header_bottom_container') && document.getElementById('header_background_color_bottom')) {
        document.getElementById('preview_header_bottom_container').style.backgroundColor = color;
        document.getElementById('header_background_color_bottom').value                  = color;
        hide('error_header_background_color_bottom');
    } else if (color && document.getElementById('preview_header_bottom_container')) {
        document.getElementById('preview_header_bottom_container').style.backgroundColor = '';
        show('error_header_background_color_bottom');
    }
}

function define_premium_preview_set_accent_color(color) {
    if (is_color(color) && document.getElementById('preview_accent_color') && document.getElementById('accent_color')) {
        document.getElementById('preview_accent_color').style.color = color;
        document.getElementById('accent_color').value               = color;
        hide('error_accent_color');
    } else if (color && document.getElementById('preview_accent_color')) {
        document.getElementById('preview_accent_color').style.color = '';
        show('error_accent_color');
    }
}

function define_premium_preview_set_ad(ad_image_url, ad_image_width, ad_image_height, ad_image_id, ad_url, ad_target) {
    document.getElementById('preview_ad').src    = ad_image_url;
    document.getElementById('preview_ad').width  = ad_image_width;
    document.getElementById('preview_ad').height = ad_image_height;
    document.getElementById('ad_image_id').value = ad_image_id;
    document.getElementById('ad_url').value      = ad_url;
    if (ad_target == '_blank') {
        document.getElementById('ad_click_target_blank').checked = true;
        document.getElementById('ad_click_target_self').checked = false;
    } else {
        document.getElementById('ad_click_target_blank').checked = false;
        document.getElementById('ad_click_target_self').checked = true;
    }
}
function define_premium_preview_set_footer_background_color_top(color) {
    if (is_color(color) && document.getElementById('preview_footer_top_container') && document.getElementById('footer_background_color_top')) {
        document.getElementById('preview_footer_top_container').style.backgroundColor = color;
        document.getElementById('footer_background_color_top').value                  = color;
        hide('error_footer_background_color_top');
    } else if (color && document.getElementById('preview_footer_top_container')){
        document.getElementById('preview_footer_top_container').style.backgroundColor = '';
        show('error_footer_background_color_top');
    }
}
function define_premium_preview_set_footer_background_color_bottom(color) {
    if (is_color(color)) {
        document.getElementById('preview_footer_bottom_container').style.backgroundColor = color;
        document.getElementById('footer_background_color_bottom').value                  = color;
        hide('error_footer_background_color_bottom');
    } else {
        document.getElementById('preview_footer_bottom_container').style.backgroundColor = '';
        show('error_footer_background_color_bottom');
    }
}
function define_premium_preview_set_gradients(isChecked) {
    if (isChecked) {
        document.getElementById('preview_header_bottom_container').style.backgroundImage = 'url(' + document.getElementById('gradient_image_url_head').value + ')';
        document.getElementById('preview_footer_top_container').style.backgroundImage = 'url(' + document.getElementById('gradient_image_url_foot').value + ')';
    } else {
        document.getElementById('preview_header_bottom_container').style.backgroundImage = 'none';
        document.getElementById('preview_footer_top_container').style.backgroundImage = 'none';
    }
}

/* color picker actions */
function colorpicker_set_header_background_color_top(color) {
    document.getElementById('header_background_color_top').value = color;
    hide_box('floating_infobox_colorpicker_header_background_color_top');
    define_premium_preview_set_header_background_color_top(color);
}
function colorpicker_set_header_background_color_bottom(color) {
    document.getElementById('header_background_color_bottom').value = color;
    hide_box('floating_infobox_colorpicker_header_background_color_bottom');
    define_premium_preview_set_header_background_color_bottom(color);
}
function colorpicker_set_accent_color(color) {
    document.getElementById('accent_color').value = color;
    hide_box('floating_infobox_colorpicker_accent_color');
    define_premium_preview_set_accent_color(color);
}
function colorpicker_set_footer_background_color_top(color) {
    document.getElementById('footer_background_color_top').value = color;
    hide_box('floating_infobox_colorpicker_footer_background_color_top');
    define_premium_preview_set_footer_background_color_top(color);
}
function colorpicker_set_footer_background_color_bottom(color) {
    document.getElementById('footer_background_color_bottom').value = color;
    hide_box('floating_infobox_colorpicker_footer_background_color_bottom');
    define_premium_preview_set_footer_background_color_bottom(color);
}

function is_color(item) {
    if (item == '') {
        return true;
    } else {
        var is_a_color = /^#[abcdef\d]{6}$/i;
        return is_a_color.test(item);
    }
}


/*   Image upload in premium   */


function define_premium_upload_background_image_start_feedback() {
    var feedback_container       = document.getElementById('upload_background_image_feedback_container');
    feedback_container.innerHTML = ikon_communicating;
    return false;
}

function define_premium_upload_background_image_finished_feedback(result) {
    eval('(' + result + ')');
}

function define_premium_set_template_id(template_id) {
    document.getElementById('template_id').value = template_id;
}

function define_premium_get_template_id() {
    return document.getElementById('template_id').value;
}

function define_premium_get_background_image(image_id) {
    var feedback_container   = document.getElementById('upload_background_image_feedback_container');
    feedback_container.innerHTML = ikon_communicating;

    var background_container = document.getElementById('widget_background_container');

    var http = getHTTPObject();
    if (http && image_id && background_container) {
        http.open(
            "POST",
            base_url + "/mq_ws.pl",
            true);

        http.onreadystatechange = function() {
            if (http.readyState == 4) {
                var re = /^<Quiz><error/;
                if (re.test(http.responseText)) {
                    // handle error ?
                } else {
                    background_container.style.backgroundImage = http.responseText;
                    feedback_container.innerHTML   = '';
                }
            }
        }

        http.send("<Quiz><GetTemplateBackgroundImage><ImageId>" + image_id + "</ImageId><Variant>backgroundStyle</Variant></GetTemplateBackgroundImage></Quiz>");
    }
}




/*   Info/help boxes   */
function show_box(received_event, box) {
    var mouse_x;
    var mouse_y;

    var loginbox_div = document.getElementById(box);

    if (loginbox_div.style.visibility == 'visible') {
      return hide_box(box);
    }

    if (received_event.pageX || received_event.pageY) {
      mouse_x = received_event.pageX;
      mouse_y = received_event.pageY;
    } else if (received_event.clientX || received_event.clientY) {
      mouse_x = received_event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      mouse_y = received_event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }

    loginbox_div.style.left = (mouse_x - 10) + 'px'; // 174 in stead of 10
    loginbox_div.style.top  = (mouse_y - 10) + 'px';

    loginbox_div.style.visibility = 'visible';
}

function hide_box (box) {
     var loginbox_div = document.getElementById(box);
     loginbox_div.style.visibility = 'hidden';
}

function show_box_existing_templates(received_event, box) {
    var mouse_x;
    var mouse_y;

    var loginbox_div = document.getElementById(box);

    if (loginbox_div.style.visibility == 'visible') {
      return hide_box(box);
    }

    if (received_event.pageX || received_event.pageY) {
      mouse_x = received_event.pageX;
      mouse_y = received_event.pageY;
    } else if (received_event.clientX || received_event.clientY) {
      mouse_x = received_event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      mouse_y = received_event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }

    loginbox_div.style.left = (mouse_x - 530) + 'px'; // 174 in stead of 10
    loginbox_div.style.top  = (mouse_y + 20) + 'px';

    loginbox_div.style.visibility = 'visible';
}

function show_box_colorpicker(received_event, box) {
    var mouse_x;
    var mouse_y;

    var loginbox_div = document.getElementById(box);

    if (loginbox_div.style.visibility == 'visible') {
      return hide_box(box);
    }

    if (received_event.pageX || received_event.pageY) {
      mouse_x = received_event.pageX;
      mouse_y = received_event.pageY;
    } else if (received_event.clientX || received_event.clientY) {
      mouse_x = received_event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      mouse_y = received_event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }

    loginbox_div.style.left = (mouse_x + 0) + 'px'; // 174 in stead of 10
    loginbox_div.style.top  = (mouse_y + 0) + 'px';

    loginbox_div.style.visibility = 'visible';
}

function display_facebook_sharer (title, image_url, summary, url) {
    window.open(
        'http://www.facebook.com/sharer.php?s=100&p[title]=' + escape(title) + '&p[images][0]=' + escape(image_url) + '&p[medium]=102&p[summary]=' + escape(summary) + '&p[url]=' + escape(url),
        'sharer',
        'width=626,height=436,resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=yes,menubar=no,copyhistory=no'
    );
}
