function clearInputRadios() {
	$('input:radio').attr('checked', false);
}

var tt;

function gotoSlide(pc, aleft, aname){
    pc.animate({
        left: -aleft
    }, {
        duration: 500,
        queue: false,
        easing: 'easeInOutCubic',
        complete: function(){
            if (aname) {
                if (aname.indexOf('_c') != -1) {
                    var n = aname.split('_c')[0];
                    var l = $('#' + n).position().left;
                    pc.css({
                        left: -l
                    });
                    window.location.href = "#" + n;
                }
                else 
                    window.location.href = "#" + aname;
                if (n=='quiz1' || aname=='quiz1') {
                 
                    tt = $('#tooltip2').removeClass('hide');
                }
            }
        }
    });
}

function moveLogos(i){
    var logo = $('#rightLogos li');
	var mediaLogoNumbers = logo.filter('.mediatamogatok').length;
	var tamogatoLogoNumbers = logo.filter('.tamogatok').length;
	var tamogatok = $('img.sponsor.tamogatok');
	var mediatamogatok = $('img.sponsor.mediatamogatok');
	
    logo.eq(0).animate({
        marginLeft: -logo.outerWidth(),
        opacity: 0
    }, {
        easing: 'easeOutQuint',
        duration: 1500,
        queue: false,
        complete: function(){
			if ( i == mediaLogoNumbers) {
				mediatamogatok.hide();
				tamogatok.show();
			}
			if ( i == logo.length - 1) {
				tamogatok.hide();
				mediatamogatok.show();
			}
			
            var c = $(this).clone();
            $(this).parent().append(c.css({
                marginLeft: 0,
                opacity: 0
            }));
            $(this).remove();
            c.animate({
                opacity: 1
            }, {
                easing: 'easeInQuint',
                duration: 1500,
                queue: false
            });
			if ( i == logo.length - 1  ) { i = 1; } else { i++; }
            moveLogos(i);
        }
    });
}

function initControl(){
    $('#emocio, #racio').hide();
    var sc = $('#sliderContainer').css({
        overflow: 'hidden',
        height: 424
    });
    $('#pFooter').css({
        paddingTop: '42px'
    });
    var pc = $('#pContent').css({
        left: '-1000px',
        width: $('#pContent').width() + 2000
    });
    var frst = pc.find('.slide:first').clone();
    frst.attr('id', frst.attr('id') + "_c");
    var lst = pc.find('.slide:last').clone();
    lst.attr('id', lst.attr('id') + "_c");
    pc.append(frst);
    pc.prepend(lst);
    
    var limitRight = sc.offset().left;
    var limitLeft = limitRight - (sc.find('div.slide').length - 1) * sc.width();
    var loc = window.location.href;
    
    var defLeft = 0;
    if (loc.indexOf('#') != -1) {
        sc.scroll(function(){
            defLeft = sc.scrollLeft();
        })
    }
    var moveb = 0;
    var movee = 0;
    var num = 1;
    var inputError = [];
    
    pc.draggable({
        axis: 'x',
        containment: [limitLeft, 0, limitRight, 421],
        cursor: 'w-resize',
        scroll: true,
        start: function(){
            moveb = $(this).offset().left;
            num = Math.round(-(moveb - limitRight) / 1000);
            inputError = checkInputs(pc.find('.slide:visible').eq(num));
        },
        stop: function(){
            movee = $(this).offset().left - moveb;
            var tmp = -($(this).offset().left - limitRight) / 1000;
            
            if (inputError.length == 0) {
                if (Math.abs(movee) > 50) {
                    if (movee < 0) 
                        tmp = Math.ceil(tmp);
                    else 
                        tmp = Math.floor(tmp);
                    var aleft = tmp * 1000 - defLeft;
                    var aname = sc.find('div.slide:visible').eq(tmp).attr('id');
                    gotoSlide(pc, aleft, aname);
                }
                else 
                    if (Math.abs(movee) != 0) {
                        tmp = Math.round(tmp);
                        gotoSlide(pc, tmp * 1000 - defLeft, false);
                    }
            }
            else {
                gotoSlide(pc, num * 1000 - defLeft, false);
                
            }
            showErrors(inputError);
        }
    });
    
    var questions = {
        'q1': '',
        'q2': '',
        'q3': '',
        'q4': '',
        'q5': ''
    };
    
    function checkInputs(par){
        var error = [];
        par.find('div p').each(function(){
            var id = $(this).attr('id');
            if (questions[id] == '') 
                error.push(id);
        });
        return error;
    }
    
    function checkResult(){
        var e = 0, r = 0, h = 0;
        for (var i in questions) {
            if (questions[i] == 'e') 
                e++;
            else 
                if (questions[i] == 'r') 
                    r++;
                else 
                    h++;
        }
        var ret = r > e ? 'racio' : 'emocio';
        if (h > 0) 
            ret = 'hiba';
        return ret;
    }
    
    function showErrors(errors){
        $('.error').removeClass('error');
        if (errors.length > 0) {
            $('.errorMsg').show();
            for (var i = 0; i < errors.length; i++) {
                $('#' + errors[i]).addClass('error');
            }
        }
        else $('.errorMsg').hide();
    }
    
    $('input[type=radio]').click(function(e){
        var id = $(this).parent().prevAll('p').attr('id');
        questions[id] = $(this).val();
    }).attr('checked', '');
    
    $('a.submitLink').click(function(e){
        var t=$(this);
        var inp=$(this).prev('span.inputField');
        var mail=inp.find('input').val();
        var flag=$(this).parents('.slide').attr('id')[0];
        $.get('./emailValidator.php?email='+mail+'&flag='+flag, function(data){
            switch(data){
                case 'hiányzó adat':
                    inp.addClass('error');
                break;
                case 'hibás email':
                    inp.addClass('error');
                break;
                case 'hibás flag':
                break;
                default:
                    inp.removeClass('error');
                    t.parents('.resultContainer').html('<p class="mt10"><strong class="resultText">E-mail címedet elmentettük, amelyen értesítünk a sorsolás eredményéről. A nyeremény, egy darab egy főre szóló kétnapos Országos Reklámkonferencia belépő amely ingyenes átjárást biztosít emocionális és racionális féltekéid között.<br/>A sorsolás időpontja: 2010. szeptember 15. A teszt kitöltésével történő regisztráció során eljuttatott adattal, a regisztráló hozzájárulását adja, hogy a konferencia szervezője – a konferencia jellege által meghatározott célból és ideig - nyilvántartsa és használja azt. A konferencia szervezője az interneten hozzá eljuttatott valamennyi adatot ugyanolyan védelemmel kezeli, mintha azokat egyéb úton bocsátották volna rendelkezésére. Ezen hozzájárulását a regisztráló bármikor visszavonhatja, a reklamkonferencia@hdgroup.hu e-mail címen.</strong></p>');
            }
        });
        e.preventDefault();
    });
    
    $('a.navigate').click(function(e){
        e.preventDefault();
        inputError = checkInputs($(this).parents('.content'));
        if (inputError.length == 0) {
            var aname;
            if ($(this).hasClass('result')) {
                aname = checkResult();
                if (aname != 'hiba') {
                    $('#emocio, #racio').hide();
                    $('#' + aname).show();
                }
            }
            else {
                aname = $(this).attr('href').split('#')[1];
            }
            if (aname != 'hiba') {
                var aleft = $('div.slide[id=' + aname + ']').offset().left - pc.offset().left - defLeft;
                gotoSlide(pc, aleft, aname)
            }
        }
        
        showErrors(inputError);
        
    });
	
	$('a.navigate.result').click(function(e){
		clearInputRadios();
		e.preventDefault();
	});
    
    $('img.infoLink').each(function(){
        var cont=$(this).nextAll('div.infoLayer').eq(0);
        var link=$(this).prev('a');
        if (cont.length == 0) {
            $(this).css({
                display: 'none'
            });
            link.css({
                cursor: 'default'
            });
        }
        else {
            $(this).addClass('hasContent');
            link.addClass('hasContent');
        }
    })
    
    $('.hasContent').live("click",function(e){
        e.preventDefault();
        var dia=$('#dialogBox');
        var cont=$(this).parent().find('div.infoLayer').clone();
        if (cont.length) {
            dia.dialog("destroy");
            dia.html(cont.html()).dialog({
                resizable: false,
                width: 561,
                modal: true,
                close: function(event, ui){
                    dia.dialog("destroy");
                }
            });
            accordions('#dialogBox');
        }
    });

    tt = $('#tooltip');
    
    pc.mouseover(function(me){
        if (!tt.hasClass('hide')) {
            tt.addClass('hide').show();
            setTimeout(function(){
                tt.hide();
            }, 5000);
        }
        
    }).mousemove(function(me){
        tt.css({
            left: me.pageX + 10,
            top: me.pageY - 80
        })
    });
}

$(document).ready(function(){
	var i = 1;
	initControl();
    $('.lightBox').lightBox();
    moveLogos(i);
});
