/******************   global variable declaration,  begin *****************/

/******************   global variable declaration,  end *******************/

/******************   class declaration,  begin *****************/

/******************   class declaration,  end *******************/

/***** init section, begin *****/
$(document).ready(
    function() {
        step5Init();
    }
    );


function step5Init()
{
    //debugLog("step5Init.");
    step5BindEvents();

    $("input[name*=step5]:radio:checked").attr("checked", "");

}

function step5BindEvents()
{
    $("#step5_brand_name").bind('change', function(e)
    {
        step5BrandChange(e);
    });

    $("#step5_type1").bind('click', function(e)
    {
        $("#step5_ddl1").show();
    });

    $("#step5_type2").bind('click', function(e)
    {
        $("#step5_ddl1").show();
    });

    $("#step5_type3").bind('click', function(e)
    {
        $("#step5_ddl1").hide();
    });
}

function verifyStep5()
{
    //debugLog("verifyStep5");
    var checkResult = true;

    // check telphone, leading char
    if(checkResult)
    {
        if($("input[name*=step5]:radio:checked").length == 0)
        {
            checkResult = false;
            tmpErrorCode = 1;
        }
    }
    
    if(checkResult)
    {
        if(!$("#step5_type3").attr("checked")){
            $("select[name*=step5]").each(function(){
                if($(this).val()=="NULL" || $(this).val()=="")
                {
                    checkResult = false;
                    tmpErrorCode = 1;
                }
            }
            );
        }
    }
    
    if(!checkResult)
    {
        switch(tmpErrorCode)
        {
            case 0:
                break;
            case 1:
                showTips("Tous les champs sont obligatoires.");
                break;
            case 2:
                showTips("!");
                break;
            default:
                break;
        }
    }

//    debugLog("trigger1:" + checkResult + " : "+ $("input[name*=step5]:radio:checked").length);
//    return false;
    return checkResult;
}

function goStep5()
{
    var params = {
        "data_format" : 'json',
        "step" : 5,
        "civility" : $("input[name='step4_civility']:checked").val(),
        "first_name" : $("#step4_first_name").val(),
        "name" : $("#step4_name").val(),
        "email" : $("#step4_email").val(),
        "postcode" : $("#step4_postcode").val(),
        "tel" : $("#step4_tel").val(),
        "track" : $("#track").val(),
        "grand_compte" : $("#grand_compte").val()
    };
    var submitUrl;

    showBlockUILoading("#eurotax_valuation_form" );

    submitUrl = BASE_URL + "eurotax/goStep5";
    //    submitUrl = BASE_URL + "eurotax/ajaxTest";

    $.ajax({
        url: submitUrl,
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            goStep5CallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            //debugLog("goStep5 Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function goStep5CallBack(jsonData)
{
    if(jsonData.info.status == operationStatus.Error)
    {
        formStatus.currentStep--;
        showTips(jsonData.info.error_info);
    }
    else
    {
    	$('#tel_rdv').val(jsonData['items']['valuationParams']['step4Params'].tel);
    	$('#id_client_rdv').val(jsonData['items']['valuationParams']['step4Params']['takebackInfo'].clientId);
    	$('#id_vehicle_rdv').val(jsonData['items']['valuationParams']['step4Params']['takebackInfo'].vehicleId);
    	
    	
        submitUrl = BASE_URL + "eurotax/getAgence";

        $.ajax({
            type: "GET",
            url: submitUrl,
            data: "codepostal=" + jsonData['items']['valuationParams']['step4Params'].postcode,
            dataType: "json",
            success: function(jsonData){
                $('#agence_adr').html(jsonData['infos']);
            }
        });
    	
        for(i=0;i<jsonData['items']['brands'].length;i++)
        {
            $('<option value="' + jsonData['items']['brands'][i].key +'">' + jsonData['items']['brands'][i].value.toUpperCase() +'</option>').appendTo("#step5_brand_name");
        }

        for(i=0;i<jsonData['items']['models'].length;i++)
        {
            $('<option value="' + jsonData['items']['models'][i].key +'">' + jsonData['items']['models'][i].value +'</option>').appendTo("#step5_beta_model_id");
        }

        // If jump Step 5 go to Step 6 after the callback which record step 4 form datas
        if ( $("#jumpStep5").val() == "yes" ) {
            formStatus.currentStep++;
            goStep6();
        }
        else {
            var json = null;
            try{
                json = jsonData['tag']['omniture'];
            }catch(err){
                json = null;
            }
            
            showStepForm(formStatus.currentStep, json);
        }
//        showTips(jsonData.info.tips);
    }
    hideBlockUI("#eurotax_valuation_form");

//   debugLog($.dump(jsonData));
}

function step5BrandChange(e)
{
    //    debugLog($(e.currentTarget).val());
    var params = {
        "data_format" : 'json',
        "brand_name": $(e.currentTarget).val()
    };
//    var submitUrl = BASE_URL + "eurotax/getModelList";
//    var submitUrl = BASE_URL + "eurotax/getAramisModelList";
    var submitUrl = BASE_URL + "eurotax/getAramisBetaModelList";


    if($(e.currentTarget).val() != "NULL"){
        showBlockUILoading("#eurotax_valuation_form" );
        $.ajax({
            url: submitUrl,
            global: true,
            type: "GET",
            data: params,
            dataType: "json",
            success: function(jsonData){
                step5BrandChangeCallBack(jsonData);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                //debugLog("step5BrandChange Error: " + $(this).dump()); // the options for this ajax request
            }
        });
    }

}

function step5BrandChangeCallBack(jsonData)
{
    if(jsonData.info.status == operationStatus.Error)
    {
        showTips(jsonData.info.error_info);
    }
    else
    {
        step5OptionsEmpty("#step5_beta_model_id");
        for(i=0;i<jsonData['items']['models'].length;i++)
        {
            $('<option value="' + jsonData['items']['models'][i].key +'">' + jsonData['items']['models'][i].value +'</option>').appendTo("#step5_beta_model_id");
        }
    }
    hideBlockUI("#eurotax_valuation_form");
//   debugLog($.dump(jsonData));
}

function step5OptionsEmpty(cleanList)
{
    $(cleanList).empty();
    $('<option value="NULL">Sélectionner</option>').appendTo("#step5_beta_model_id");
}

