var config = new Object();
config.databaseUrl = 'data.xml';
config.anchorVariableSeparator = '&';
config.activeThemeId = 't2';
config.activeQuestionId = 'k22';
config.activeTagId = 'k22';
config.xml = new Object();
config.ratingValue = 5;
config.ratingCookieName = "edu_rating";
config.ratingJsonUrl = "http://studioszeraf.hu/cb/edukacio/jsonteszt.php";
config.questionlistUlHeight = 200;
config.questionlistUlHeightCorrection = 0;
config.formUrl = "https://www.citibank.com/hungary/consumer/igenyles2/edu/form.htm";
config.questionListMouseOver = false;


$(function() {
	init_page();
});





function init_page(){

    $(".layer").click(function(){
        display_questionlist(false);
    });


    $(".formlink a").click(function(){
        $.nyroModalManual({
              url: config.formUrl,
              forceType: 'iframe',
              width:553,
              height: 475,
              hideContent: hideContent2
        });
        return false;
    });

    $("#slider").slider({
        step: 1,
        min: 0,
        max: 10,
        values: [5],
        animate: true,
        change: function(event, ui) {
            config.ratingValue = ui.value;
        }
    });

    //adatbazist betoltjuk
    $.ajax({
        type: "GET",
        url: config.databaseUrl,
        dataType: "xml",
        success: function(xml){

            //elmentjuk a kapott adatbazist
            config.xml = $(xml);

            //url anchor-bol kiszedjuk az infokat
            get_requested_anchor_data();

            //betoltjuk az adatokat
            load_data();

            //szavazast inicializaljuk
            init_rating();

        }
    });
}



function load_data(){
    //temakat betoltjuk
    var html = '';
    config.xml.find('tema').each(function(){
        var css_class = ( config.activeThemeId == $(this).attr('id') )?' class="active"':'';
        html += '<a href="#tema='+$(this).attr('id')+'"'+css_class+'>'+$(this).attr('name')+'</a> - ';
    });
    html = html.substring(0,html.length-2);
    $("p.themes").html(html);

    //h2
    if(config.activeThemeId != ''){
        config.xml.find('tema[id="'+config.activeThemeId+'"]').each(function(){
            var html = '<b>'+$(this).attr('name')+':</b> kérdések';
            $("h2.title").html(html);
        });
    }
    if(config.activeTagId != ''){
        config.xml.find('cimke[id="'+config.activeTagId+'"]').each(function(){
            var html = 'Címke: <b>'+$(this).text()+'</b>';
            $("h2.title").html(html);
        });
    }



    //kérdéslista
    if(config.activeThemeId != ''){
        config.xml.find('tema[id="'+config.activeThemeId+'"]').each(function(){
            var html = '<a href="#" class="scroll_up">fel</a><div class="ulcnt"><ul>';
            var counter = 0;
            $(this).children("kerdes").each(function(){
                var css_class = ( config.activeQuestionId == $(this).attr('id') )?' class="question active"':' class="question"';
                var li_css_class = (counter == 0)?' class="first"':' class=""';
                if( config.activeQuestionId == $(this).attr('id') )li_css_class=li_css_class.replace('class="', 'class="selected ');
                html += '<li '+li_css_class+'><a href="#kerdes='+$(this).attr('id')+'"'+css_class+'><span>'+$(this).attr('name')+'</span></a></li>';
                if( config.activeQuestionId == $(this).attr('id') ){
                    var qhtml = '<a href="#kerdes='+$(this).attr('id')+'" class="active">'+$(this).attr('name')+'</a><div class="btn"></div>';
                    $("div.question").html(qhtml);
                }
                counter++;

            });
            html += '</ul></div><a href="#" class="scroll_down">le</a><div class="separator"></div><div class="btn"></div>';
            $("div.questionlist").html(html);
            $("div.questionlist .ulcnt").css("height", config.questionlistUlHeight);
        });
    } else if(config.activeTagId != ''){
        var html = '<a href="#" class="scroll_up">fel</a><div class="ulcnt"><ul>';
        config.xml.find('tema').each(function(){
            var counter = 0;
            $(this).children("kerdes").each(function(){
                var cimkek_teszt = $(this).find('cimke[id="'+config.activeTagId+'"]').length;
                if(cimkek_teszt > 0){
                    var css_class = ( config.activeQuestionId == $(this).attr('id') )?' class="question active"':' class="question"';
                    var li_css_class = (counter == 0)?' class="first"':' class=""';
                    if( config.activeQuestionId == $(this).attr('id') )li_css_class=li_css_class.replace('class="', 'class="selected ');
                    html += '<li '+li_css_class+'><a href="#kerdes='+$(this).attr('id')+'"'+css_class+'><span>'+$(this).attr('name')+'</span></a></li>';
                    if( config.activeQuestionId == $(this).attr('id') ){
                        var qhtml = '<a href="#kerdes='+$(this).attr('id')+'" class="active">'+$(this).attr('name')+'</a><div class="btn"></div>';
                        $("div.question").html(qhtml);
                    }
                    counter++;
                }
            });
        });
        html += '</ul></div><a href="#" class="scroll_down">le</a><div class="separator"></div><div class="btn"></div>';
        $("div.questionlist").html(html);
        $("div.questionlist .ulcnt").css("height", config.questionlistUlHeight);
    }


    //aktív kérdés betöltése
    config.xml.find('kerdes[id="'+config.activeQuestionId+'"]').each(function(){
        $("div.question a").html($(this).attr('name'));
        var html = $(this).children('valasz').text();
        $("div.answer").html(html);
        //cimkek
        var html = '';
        $(this).children("cimkek").children("cimke").each(function(){
            var css_class = ( config.activeQuestionId == $(this).attr('id') )?' class="active"':'';
            html += '<a href="#cimke='+$(this).attr('id')+'"'+css_class+'>'+$(this).text()+'</a>, ';
        });
        if(html.length > 0){
            html = '<b>címkék:</b> '+html.substring(0,html.length-2);
            $("span.tags").html(html);
        } else {
            $("span.tags").html('');
        }
    });

    //cimkekre kattintast lekezeljuk
    $("span.tags a").click(function(){
        var c = $(this).attr("href");
        tmp = c.split("#cimke=");
        if(tmp[1] != null)c = tmp[1];
        else c = '';

        config.activeTagId = c;
        config.activeQuestionId = get_random_question_of_tag(c);
        config.activeThemeId = '';

        //betoltjuk az adatokat
        load_data();
        //szavazast inicializaljuk
        init_rating();

        return true;
    });

    //temakra kattintast kezeljuk
    $("p.themes a").click(function(){
        var c = $(this).attr("href");
        tmp = c.split("#tema=");
        if(tmp[1] != null)c = tmp[1];
        else c = '';

        config.activeThemeId = c;
        config.activeQuestionId = get_random_question_of_theme(c);
        config.activeTagId = '';

        //betoltjuk az adatokat
        load_data();
        //szavazast inicializaljuk
        init_rating();

        return true;
    });

    //kerdesre kattintast kezeljuk
    $("div.questionlist a.question").click(function(){
        var c = $(this).attr("href");
        tmp = c.split("#kerdes=");
        if(tmp[1] != null)c = tmp[1];
        else c = '';

        config.activeQuestionId = c;


        if(config.activeTagId != ''){
            //ha cimkeket bongeszunk
            config.activeThemeId = '';
        } else {
            //ha temat
            config.activeThemeId = get_theme_id_of_question(c);
            config.activeTagId = '';
        }


        //betoltjuk az adatokat
        load_data();
        //szavazast inicializaljuk
        init_rating();
        display_questionlist(false);

        return true;
    });




    //kerdesre kattintast kezeljuk
    $("div.question a").click(function(){
        display_questionlist(true);
        return true;
    });

    init_height();



    $("div.questionlist").css("display", "none");
}


function show_scroll_arrows(){
    var ulh = $("div.questionlist ul").innerHeight();
    $("div.questionlist ul").css("top", "0px");


    if(ulh > config.questionlistUlHeight){
        $("div.questionlist a.scroll_up").css("display", "block");
        $("div.questionlist a.scroll_down").css("display", "block");
    }
    var o1 = $("div.questionlist ul li.selected").offset();

    if(ulh < config.questionlistUlHeight){
        $("div.questionlist ul").css("top", "0px");
    }

    var o2 = $("div.questionlist ul").offset();
    var offset_top = (o1.top-o2.top);

    //if(ulh > config.questionlistUlHeight){
        var correction = config.questionlistUlHeight - offset_top - config.questionlistUlHeight;
        config.questionlistUlHeightCorrection = 0;

        //alert("1: "+correction);
        for(var i = 0; i<10; i++){
            if((correction*(-1)+config.questionlistUlHeight) > ulh){correction+=10;config.questionlistUlHeightCorrection+=10;}
        }
        //alert("2: "+correction);
        $("div.questionlist ul").css("top", correction+"px");

        if(ulh < config.questionlistUlHeight){
            config.questionlistUlHeightCorrection=(o1.top-o2.top);
            $("div.questionlist ul").css("top", "0px");
        }
    //}
    init_scroll_arrows();

}

function init_scroll_arrows(){
    var ulh = $("div.questionlist ul").innerHeight();

    $("div.questionlist a.scroll_down").mouseover(function(){
        show_scroll_arrows2("up", -10);
        var newtop =  (0-(ulh-config.questionlistUlHeight));
        //alert($("div.questionlist ul").css("top") + "->" + newtop+ ":" +ulh+ "-" +config.questionlistUlHeight);
        $("div.questionlist ul").animate({top: newtop+'px'}, 1000, "", function(){show_scroll_arrows2("down", newtop);} );
    });
    $("div.questionlist a.scroll_down").mouseout(function(){
        $("div.questionlist ul").stop();
    });

    $("div.questionlist a.scroll_up").mouseover(function(){
        show_scroll_arrows2("down", -10);
        var newtop =  0;
        //alert($("div.questionlist ul").css("top") + "->" + newtop);
        $("div.questionlist ul").animate({top: newtop+'px'}, 1000, "", function(){show_scroll_arrows2("up", newtop);} );
    });
    $("div.questionlist a.scroll_up").mouseout(function(){
        $("div.questionlist ul").stop();
    });



}

function show_scroll_arrows2(arr, targ){
    var p = $("div.questionlist ul").css("top");
    p = parseInt(p);
    if(p == targ)$("div.questionlist a.scroll_"+arr).css("display", "none");
    else $("div.questionlist a.scroll_"+arr).css("display", "block");
}

function display_questionlist(m){
    var o = $("div.question").offset();
    var o2 = $("div.edubox").offset();
    x = o.top-o2.top-133;
    var qtop = x - config.questionlistUlHeightCorrection;

    $("div.questionlist").css("top", qtop+"px");

    if(m == true){
        $("div.questionlist").css("display", "block");
        //$("div.question").css("display", "none");
        $(".layer").css("width", ($("body .content").width()-10)+"px");
        $(".layer").css("height", ($("body .content:eq(0)").height()+$("body .content:eq(1)").height()+$("body .content:eq(2)").height()-10)+"px");

        $(".layer").css("display", "block");

        var ulh = $("div.questionlist ul").innerHeight();
        if(ulh < config.questionlistUlHeight){
            $("div.questionlist a.scroll_up").css("display", "none");
            $("div.questionlist a.scroll_down").css("display", "none");
        } else {
            $("div.questionlist a.scroll_up").css("display", "block");
            $("div.questionlist a.scroll_down").css("display", "block");
        }

    show_scroll_arrows();

    } else {
        $("div.questionlist").css("display", "none");
        $(".layer").css("display", "none");
        //$("div.question").css("display", "block");
    }
    return true;
}

function init_rating(){
    $("#slider").slider('destroy');
    var cr = get_rating_from_cookie();
    $("#slider").slider({
        step: 1,
        min: 0,
        max: 10,
        values: [cr],
        animate: true,
        change: function(event, ui) {
            config.ratingValue = ui.value;
        }
    });

    //szavazasgomb
    $("#rating_button").click(function(){
        //lementjuk kukiba config.ratingCookieName
        var c = getCookie(config.ratingCookieName);
        if(c == null)c = '';

        c = c + config.activeQuestionId + "-"+config.ratingValue+":";
        expires = 1 * 60*60*24*1000;
		var today = new Date();
		var expires_date = new Date( today.getTime() + (expires) );


        setCookie(config.ratingCookieName, c, expires_date);

        //json-nal elkuldjuk
        $.getJSON(config.ratingJsonUrl+'?qid='+config.activeQuestionId+'&rating='+config.ratingValue+'&jsoncallback=?', function(json){
            var result_num = json.num;
        });
        //eltuntetjuk a szavazas boxot
        rating_activate();
        return false;
    });

    rating_activate();
    return true;
}


function rating_activate(){
    //megnezzuk h adott szavazas idje szerepel-e a kukiban
    //ha igen, inaktivaljuk
    var c = getCookie(config.ratingCookieName);
    if(c == null)c = '';

    var tmp = c.split(":");
    var tmp_arr = new Array();
    for(var i = 0; i < tmp.length; i++){
        tmp2 = tmp[i].split("-");
        tmp_arr[tmp_arr.length] = tmp2[0];
    }
    var tmp = tmp_arr;


    if(jQuery.inArray(config.activeQuestionId, tmp) != -1){
        $(".szavazas .inactivator").css("display", "block");
    } else {
        $(".szavazas .inactivator").css("display", "none");
    }
}

function get_rating_from_cookie(){
    var c = getCookie(config.ratingCookieName);
    if(c == null)c = '';
    var tmp = c.split(":");
    for(var i = 0; i < tmp.length; i++){
        var tmp2 = tmp[i].split("-");
        if(tmp2[0] == config.activeQuestionId)return parseInt(tmp2[1]);
    }
    return 5;
}

function get_requested_anchor_data(){
    var atext = '';
    tmp_tema = tmp_kerdes = tmp_cimke = '';

    var tmp = location.href.split("#");
    if(tmp.length == 1)atext = '';
    else atext = tmp[1];

    var tmp = atext.split(config.anchorVariableSeparator);
    for(var i = 0; i < tmp.length; i++){
        var tmp2 = tmp[i].split("=");
        if(tmp2[0] == "tema")tmp_tema = tmp2[1];
        if(tmp2[0] == "kerdes")tmp_kerdes = tmp2[1];
        if(tmp2[0] == "cimke")tmp_cimke = tmp2[1];
    }

    //lehetosegek
    if(tmp_kerdes != '' && tmp_tema != ''){
        //1. kerdes id-t es tema id-t kapunk
        config.activeThemeId = tmp_tema;
        config.activeQuestionId = tmp_kerdes;
    } else if(tmp_kerdes != '' && tmp_tema != ''){
        //2. kerdes id-t es cimke id-t kapunk
        config.activeTagId = tmp_cimke;
        config.activeQuestionId = tmp_kerdes;
    } else if(tmp_tema != '' && tmp_kerdes == '' && tmp_cimke == ''){
        //3. csak tema id-t kapunk: kerdes random
        config.activeThemeId = tmp_tema;
        config.activeQuestionId = get_random_question_of_theme(tmp_tema);
    } else if(tmp_cimke != '' && tmp_kerdes == '' && tmp_tema == ''){
        //4. csak cimke id-t kapunk: kerdes random
        config.activeTagId = tmp_cimke;
        config.activeQuestionId = get_random_question_of_tag(tmp_cimke);
        config.activeThemeId = '';
    } else if(tmp_kerdes != '' && tmp_cimke == '' && tmp_tema == ''){
        //5. csak kerdes id-t kapunk: tema id-t kiszamoljuk
        config.activeQuestionId = tmp_kerdes;
        config.activeThemeId = get_theme_id_of_question(config.activeQuestionId);
        config.activeTagId = '';
    } else {
        //6. véletlenszerű téma véletlenszerű kérdése
        config.activeThemeId = get_random_theme();
        config.activeQuestionId = get_random_question_of_theme(config.activeThemeId);
        config.activeTagId = '';
    }
}


function get_theme_id_of_question(qid){
    var tid = '';
    config.xml.find('kerdes').each(function(){
        if($(this).attr('id') == qid){
            tid = $(this).parent("tema").attr('id');
        }
    });
    return tid;
}

function get_random_theme(){
    var arr = new Array();
    config.xml.find('tema').each(function(){
        arr[arr.length] = $(this).attr('id');
    });
    arr.sort( randOrd );
    arr[arr.length] = 'a';
    return arr[0];
}

function get_random_question_of_theme(tid){
    var arr = new Array();
    config.xml.find('tema[id="'+tid+'"]').each(function(){
        $(this).children("kerdes").each(function(){
            arr[arr.length] = $(this).attr('id');
        });
    });
    arr.sort( randOrd );
    arr[arr.length] = 'a';
    return arr[0];
}

function get_random_question_of_tag(tid){
    var arr = new Array();
    config.xml.find('tema').each(function(){
        $(this).children("kerdes").each(function(){
            $(this).children("cimkek").children("cimke").each(function(){
                if($(this).attr('id') == tid){
                    arr[arr.length] = $(this).parent("cimkek").parent("kerdes").attr('id');
                }
            });
        });
    });
    arr.sort( randOrd );
    arr[arr.length] = 'a';
    return arr[0];
}

//kiegesztito fuggvenyek

$.fn.tagName = function() {
    return this.get(0).tagName.toLowerCase();
}

function randOrd(){return (Math.round(Math.random())-0.5); }


function init_height(){
    var ch = $(".edubox .container").height();
    $(".edubox").height(ch + 130);
}

function form_close(){
	$.nyroModalRemove();
}
function hideContent2(elts, settings, callback) {
	elts.contentWrapper.hide();
	callback();
}

