/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

function showForm ( color ){
    jQuery('form[name="formStep1"] :text').each(function(){
         if(jQuery(this).val() != ''){
            jQuery(this).trigger('keyup');
        }
    });
    jQuery('form[name="formStep2"] :text').each(function(){
         if(jQuery(this).val() != ''){
            try{
                jQuery(this).triggerHandler('keyup');
            }catch(e){
                
            }
        }
    });
    
    jQuery('.button').addClass(color);
    
    if(formEffect == 'slide') {
		jQuery("#formContainer")
			.animate(
				{"left": "-="+marginForm+"px"}, { 
					duration: 570,
					easing: 'easeOutExpo'
				});
	}
	else if(formEffect == 'fade') {
		jQuery("#formContainer").hide();
		jQuery("#formContainer").css('left', '-'+marginForm+'px');
        
        if(idNumberEnquete == 384){
            setTimeout(function(){
            jQuery("#formContainer").fadeIn('slow');
            },200);
            
            jQuery('.questionNumber').addClass(color);
        }
        else{
            jQuery("#formContainer").fadeIn('slow');
        }
	}
    
    //set header above flash
    if(idNumberEnquete == 380){
        jQuery('.header').addClass(color);
        jQuery('.questionNumber').addClass(color);
        
        jQuery('#flashContainer').css('z-index','99');
    }
    
    if(idNumberEnquete == 381){
        jQuery('.questionNumber').addClass(color);
    }
    
    setTimeout(function(){ jQuery("#agreementBoxText").animate({ scrollTop: jQuery("#agreementBoxText").prop("scrollHeight") - jQuery('#agreementBoxText').height() }, 500) }, 1000);
}
var timeOut = null;
jQuery(document).ready(function(){
      
    /* Dialogs for Agreements and Privacy Statement */
    jQuery('#termsClick, #termsClick2').bind('click', function() {        
        jQuery('#termsText').dialog({autoOpen: false, draggable: false, resizable: false, width: 550, height: 500, modal: true, closeOnEscape: true});
        jQuery('#termsText').dialog("open").scrollTop(0);
    });
            
    jQuery('#privacyClick, #privacyClick2, #privacyClick3').bind('click', function() {
        jQuery('#privacyStatementText').dialog({autoOpen: false, draggable: false, resizable: false, width: 550, height: 500, modal: true, closeOnEscape: true});
        jQuery('#privacyStatementText').dialog("open").scrollTop(0);
    });
	
    
    /* Label fader in input fields */
    jQuery('form[name="formStep1"] :text').jLabel();
    jQuery('form[name="formStep2"] :text').jLabel();
    jQuery("input").attr("autocomplete","off");
      
    /* Set the inputs to only numeric. */
    jQuery('#postcode1').numeric();
    jQuery('#huisnummer').numeric();
    jQuery('#telefoonnummer').numeric();
    
    /* Function activated on click .buttonNext */
    jQuery('div.buttonNext').one('click',function(e){
        jQuery(this).html('<div class="loading">'+jQuery(this).html()+'</div>');
        nextStepFrom.apply(this,[e]);
    });
	
    /* Set div height for step 2 (IE7 fix) */	
    var step1height = jQuery('div#Step1').height();
    var step2height = jQuery('div#Step2').height();

    if(step1height < minFormHeight) {
            jQuery('div#Step1').css('height', minFormHeight+'px');
    }
    if(step2height < minFormHeight) {
            jQuery('div#Step2').css('height', minFormHeight+'px');
    }
    else {
            jQuery('div#Step2').css('height', step2height+'px');
    }
});

function nextStepFrom() {

        //jQuery('div.buttonNext').addClass( 'loading' );

        /* If fields are changed then delete tooltip and 'wrong' class */
        jQuery("input").keyup(function(){ checkValues (this); });
        jQuery("select").bind('change', function(){ checkValues (this); });
        jQuery("input[type=checkbox]").bind('change', function(){ checkValues (this); });
        jQuery("input[type=radio]").bind('change', function(){ checkValues (this); });
        
        //if(jQuery(this).parent().parent().attr('id') == 'Step2'){
             
           
         //}
        /* Check if fields are empty. If so give them 'wrong' class and tooltip. */
        var check = 0;
        var widget = this;
        var site_id = jQuery('input[name="site_id"]').val();
        
        jQuery(this).parent().find('input, textarea, select').each(function(){
            if(jQuery(this).attr('id') == 'telefoonnummer' && jQuery('#mobielenummer').val() != '') {
                jQuery('#telefoonnummer').removeClass('wrong');
            } else if((jQuery(this).attr('id') == 'mobielenummer') && (jQuery('#telefoonnummer').val() != '')) {
                jQuery('#mobielenummer').removeClass('wrong');
            } else {
                if((!jQuery(this).val() && jQuery(this).attr('id') != 'tussenvoegsel' && jQuery(this).attr('id') != 'toevoeging' && 
                    jQuery(this).attr('type') != 'hidden' ) || (jQuery(this).attr('type') == 'checkbox' && 
                    jQuery(this).attr('checked') == undefined && jQuery(this).attr('id') != 'privacyStaatsloterij' && 
                    jQuery(this).attr('id') != 'privacyBesparenkan' && jQuery(this).attr('id') != 'privacyWarchild' /*&& jQuery(this).attr('id') != 'privacyPowertothePeople'*/ ) 
                    ) {

                    if((jQuery(this).attr('id') == 'privacy2' || jQuery(this).attr('id') == 'coregAgreement') && site_id == '1977'){
                        return;
                    } else{
                    if(check == 0) {
                        if(jQuery(this).attr('id') == 'privacy' || jQuery(this).attr('id') == 'coregAgreement') {
                            jQuery("#agreementBoxText").animate({ scrollTop: jQuery("#agreementBoxText").prop("scrollHeight") - jQuery('#agreementBoxText').height() }, 500);
                        }
                            
                        showTooltip('#'+jQuery(this).attr('id'));
                        jQuery(this).focus();
                            resetClickButton();
                        jQuery(widget).unbind('click').one('click',function(e){
                            jQuery(widget).html('<div class="loading">'+jQuery(widget).html()+'</div>');
                            nextStepFrom.apply(this,[e]);
                        });
                        
                    }

                    check = 1;
                    }
                    /* Uitzondering maken voor de extra tekst met Co-regs. */
                    if(jQuery(this).attr('id') == 'privacy' || (jQuery(this).attr('id') == 'privacy2' && site_id != 1977) || jQuery(this).attr('id') == 'privacyStaatsloterij' || jQuery(this).attr('id') == 'privacyBesparenkan' || jQuery(this).attr('id') == 'privacyWarchild' || /*jQuery(this).attr('id') == 'privacyPowertothePeople' || */jQuery(this).attr('id') == 'coregAgreement') {
          
                        jQuery('.'+jQuery(this).attr('id')+'text').addClass('wrong');
                        resetClickButton();
                    } else {
                        jQuery('#'+jQuery(this).attr('id')).addClass('wrong');
                        resetClickButton();
                    }
                }
            }
        });
        
        if(check == 0) {
            var currentStep = jQuery(this).parent().parent();
            var formStep = '';
            
            var firstForm = jQuery("form[name='formStep1']");
            var secondForm = jQuery("form[name='formStep1'], form[name='formStep2']");
            var thirdForm = jQuery("form[name='formStep1'], form[name='formStep2'], form[name='formStep3']");
            
            if(currentStep.attr('id') == 'Step1') {
                formStep = firstForm;
            } else if(currentStep.attr('id') == 'Step2') {
                formStep = secondForm;
            } else if(currentStep.attr('id') == 'Step3') {
                formStep = thirdForm;
            }
            var widget = this;
            
            /* Post the fields */
            jQuery.post("/enquetes/enqueteMBE/postscripts/"+jQuery(this).parent().attr('name')+".php?id="+idNumberEnquete, jQuery(formStep).serialize(), function(xml){
                if(jQuery('result',xml).attr('success') == 'true'){
                    
                    var thisStep = currentStep;
                    var nextStep = thisStep.nextUntil('div.step').next();

                    thisStep.fadeOut('fast', function(){
                        nextStep.fadeIn('fast');
                        resetClickButton();
                        jQuery('form[name="formStep2"] :text').jLabel(); 
                    });
                    
                    jQuery('form[name="formStep1"] :text').jLabel(); 
                    jQuery("input").attr("autocomplete","off");
                    
                    var $_GET = {};

                    document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
                        function decode(s) {
                            return decodeURIComponent(s.split("+").join(" "));
                        }

                        $_GET[decode(arguments[1])] = decode(arguments[2]);
                    });
                                   
                                            if(currentStep.attr('id') == 'Step1'){
                                                jQuery(window).unbind("beforeunload").bind("beforeunload",function(e){
                                                    var advertisers = collectAdvertisers(),
                                                        coregsStep1 = collectCoregs(1);
                                                        //coregsStep2 = collectExtraCoregs();
exitPageText = "Hartelijk dank voor uw bezoek aan onze website.\n\
Indien u een prijs heeft gewonnen zullen we contact met u opnemen.\n\
\n\
De door u in de enqu\u00EAte ingevulde persoonsgegevens worden opgeslagen in het bestand van Scoot. De persoonsgegevens zullen in overeenstemming met het Privacystatement worden verwerkt.\n\
In de enqu\u00EAte heeft u aangegeven dat u van de volgende adverteerders informatie wenst te ontvangen: \n\
\n\
"+coregsStep1+"\n\
"+advertisers;


                                                    alert(exitPageText);
                                                });
                                            }
                                            
                    if(currentStep.attr('id') == 'Step2'){
                                            jQuery(window).unbind("beforeunload").bind("beforeunload",function(){
//                                            var exitPageText = "Uw deelname is bevestigd.",
//                                                $_GET = getGetRequest();

//                                                if( $_GET["dtg"] == 'ja2' ) {
                                                var advertisers = collectAdvertisers(),
                                                    coregsStep1 = collectCoregs(1),
                                                    coregsStep2 = collectCoregs(2),
                                                    coregsExtraStep2 = collectExtraCoregs();
exitPageText = "Hartelijk dank voor uw bezoek  aan onze website.\n\
Indien u een prijs heeft gewonnen zullen we contact met u opnemen.\n\
\n\
De door u in de enqu\u00EAte ingevulde persoonsgegevens worden opgeslagen in het bestand van Scoot. De persoonsgegevens zullen in overeenstemming met het Privacystatement worden verwerkt.\n\
In de enqu\u00EAte heeft u aangegeven dat u van de volgende adverteerders informatie wenst te ontvangen: \n\
\n\
"+coregsStep1+"\n\
"+coregsStep2+"\n\
"+coregsExtraStep2+"\n\n\
"+advertisers;
//                                                }

                                                alert(exitPageText);
                                            });
                        
                        // Only track when user is not duplicated or blacklisted
                        if ( jQuery( 'result', xml ).attr ( 'duplicate' ) == 'false' && jQuery( 'result', xml ).attr ( 'bl' ) == 'false' ) {
                            jQuery.getScript ( '/enquetes/enqueteMBE/html_inc/js/trackingpixels.js', function( ) {} );
                        }
                    }
                    
                }else{
                    jQuery('result > message', xml).each(function(){  
                        if(jQuery(this).attr('name') != ''){
                            if(jQuery(this).attr('name') == 'mobiel') {
                                showTooltip('#mobielenummer');
                                jQuery('#mobielenummer').addClass('wrong');
                                resetClickButton();
                            }
                            if(jQuery(this).attr('name') == 'telabbo') {
                                showTooltip('#telefoonnummer');
                                jQuery('#telefoonnummer').addClass('wrong');
                                resetClickButton();
                            } else {
                                showTooltip('#'+jQuery(this).attr('name'));
                                jQuery('#'+jQuery(this).attr('name')).addClass('wrong');
                                resetClickButton();
                            }
                                jQuery(widget).unbind('click').one('click',function(e){
                                jQuery(widget).html('<div class="loading">'+jQuery(widget).html()+'</div>');
                                nextStepFrom.apply(this,[e]);
                            });
                        }
                    });
                }
            });
        }
    };

function showTooltip (field) {
    if(jQuery('#tooltip').css('display') == 'none' || jQuery('#tooltip').css('display') == undefined) {
        if(field == '#privacy' || field == '#coregAgreement') {
            setTimeout(function(){jQuery(field).tooltip()}, 1000);
        } else {
            jQuery(field).tooltip();
        }
    }
}
    
function checkValues(field) {
    var fieldId = field.id;
	var site_id = jQuery('input[name="site_id"]').val();
	
    if(field.id == 'privacy' || field.id == 'privacyStaatsloterij' || field.id == 'privacyBesparenkan' || field.id == 'privacyWarchild' || /*field.id == 'privacyPowertothePeople' || */field.id == 'coregAgreement') {
        field = jQuery('.'+fieldId+'text');
        jQuery(field).removeClass('wrong');
        
        if(jQuery('#tooltip').css('display') != 'none'){
            jQuery('#tooltip').hide('drop', {direction: 'up'}, function() {
                jQuery(this).remove();
            });
        }
    } else {
        if(jQuery(field).val() != '') {
            jQuery(field).removeClass('wrong');
            
            if(jQuery('#tooltip').css('display') != 'none'){
                jQuery('#tooltip').hide('drop', {direction: 'up'}, function() {
                    jQuery(this).remove();
                });
            }
        }
    }
}

function getAddress ( ) {
    var postcode1	= jQuery('#postcode1').val();
    
    if(postcode1 != '' ){
        jQuery.post("/enquetes/ajax/prefillbelgium.php",
        {postcode1:postcode1},
        function(data) {
            jQuery('#plaats').empty();
            jQuery.each(data, function(name, value) {
                plaats = jQuery.trim(value.plaats);
                
                htmlOption = '<option value="'+plaats+'">'+plaats+'</option>';
                jQuery('#plaats').append(htmlOption);
            });
            
        }, "json");
    }
}

function hidePrivacy2Field() {
	jQuery("#Step2 div.agreement").hide();
	jQuery("#Step2 div.extraAgreement").css("margin-top", "20px");
	jQuery("#privacy2").attr("checked", true);
}

function resetClickButton() {
    jQuery('.button').each(function() {
        jQuery(this).html('');
    });
}

function collectCoregs(step){
    var coregs = '';

    $$('input[name="coregs_step_'+step+'"]').each(function(e,index){
        coregs += $F(e)+"\n";
    });
    
    return coregs.strip();
}

function collectExtraCoregs () {
    var extraCoregs = '';
    var coregId     = '';
    
    jQuery('.privacyExtraCoreg').each(function(e,index){
        if(jQuery(index).children('input:first').attr('checked') == 'checked'){
            coregId = jQuery(index).children('input:first').attr('id');
            extraCoregs += coregId.substring('7', coregId.length)+"\n";
        }
    });
    
    return jQuery.trim(extraCoregs);
}

function collectAdvertisers(){
    var advertisers = '';

    $$('input[name="advertisers"]').each(function(e,index){
        var questionNum = $(e).readAttribute('id').gsub(new RegExp('[^0-9]'),'');

        if(questionHasPositiveAnswer(questionNum) && $(e).readAttribute('value') != ''){
            advertisers += questionNum+". "+$F(e)+"\n";
        }
    });
    
    return advertisers.strip();
}

function questionHasPositiveAnswer(id){
    var isPositive = false;
    
    $$('input[name="vraag'+id+'"]').each(function(e,index){
        if($F(e)){
            if($F(e).startsWith('ja')){
                isPositive = true;
            }
        }
    });

    return isPositive;
}

