$(function(){
/*
	if (!jQuery.browser.msie || (jQuery.browser.version >= 7 && jQuery.browser.msie))
		$('head').append('<link href="/styles/card.css" media="screen" rel="stylesheet" type="text/css" />');
*/

    $('input, select, textarea, button', '#cardListCalculator').keydown(function(e){
        if ( e.which == 9){
            e.preventDefault();
            e.stopImmediatePropagation();
            e.stopPropagation();
        }
    });
    
    $('#cardListCalculator').submit(function(e){
        e.preventDefault();
        e.stopImmediatePropagation();
        e.stopPropagation();
    });

    $('#steptwo, #backtotwo, #tosteptwo').click(function(){
        if ( checkSteps() != true ) return alert(checkSteps());
        $('.cardquotationcustomerwelkome').hide('slow');
        gotoStep('two');
    });
    
    $('#stepthree, #backtothree, #tostepthr').click(function(){
        if ( checkSteps() != true ) return alert(checkSteps());
        $('.cardquotationcustomerwelkome').hide('slow');
        gotoStep('three');
    });
    
    $('#stepfour, #tostepfou').click(function(){
        if ( checkSteps() != true ) return alert(checkSteps());
        $.ajax({
            url:'/support/index/do-math',
            data: getFormValues(),
            dataType: 'json',
            type: "POST",
            success: function(response){
                if(response['status'] == 'ko') {
                    alert(response['error']);
                } else if (response['status'] == 'login') {
                    alert('Devi effettuare il login per vedere i prezzi.');
                    return false;
                } else {
                    $('.cardquotationcustomerwelkome').hide('slow');

                    var costo = response['costo'] / 1000;
                    $('#costounitario').val( costo + " €" );

                    var costototale = costo * response['form']['costoCardQuantita'];
                    costototale = Math.round(costototale * Math.pow(10, 2)) / Math.pow(10, 2);
                    $('#costototale').val( costototale + " €" );
                    gotoStep('four');
                    return true;
                }
            },
            error: function(response){
                alert("C'è stato un disservizio, si prega di riprovare più tardi, \r\nnel caso il problema persista si prega di contattarci.");
            }
        });
    });
    
    $('#backtoone, #tostepone').click(function(){
        //$('.cardquotationcustomerwelkome').show('slow');
        gotoStep('one');
    });

	/*
	 * Setup inline help
	 * 
	 */
	$('#cardHelp span').hide();
	$('#hlp').show();
	
	// setup eventi inline help
	$('#costoCardQuantita').click(function(){$('#cardHelp span').hide();$('#qty').show('slow');});
	$('#firma').click(function(){$('#cardHelp span').hide();$('#frm').show('slow');});
	$('#coloreserigrafico').click(function(){$('#cardHelp span').hide();$('#srg').show('slow');});
	$('#colorepantone').click(function(){$('#cardHelp span').hide();$('#pnt').show('slow');});
	$('#punzonatura').click(function(){$('#cardHelp span').hide();$('#pnz').show('slow');});
	$('#asolaturacard').click(function(){$('#cardHelp span').hide();$('#asl').show('slow');});
	$('#nomeprogettocard').click(function(){$('#cardHelp span').hide();$('#nme').show('slow');});
	$('#note').click(function(){$('#cardHelp span').hide();$('#nte').show('slow');});
	$('#chipcontatto').click(
			function() {
					$('#cardHelp span').hide();
					switch($('#chipcontatto').val()){
						case 'no':$('#nochip').show('slow');break;
						case 'sle4442':$('#chpSLE4442').show('slow');break;
						case 'sle4428':$('#chpSLE4428').show('slow');break;
						case 'sle5542':$('#chpSLE5542').show('slow');break;
						case 'at24c04':$('#chpAT24C04').show('slow');break;
						default: $('#cnt').show('slow');break;
					}
				}
		);
	$('#chipcrfid').click(
			function() {
					$('#cardHelp span').hide();
					switch($('#chipcrfid').val()){
						case 'no':$('#chpnorfid').show('slow');break;
						case 'em4100':$('#chpEM4100').show('slow');break;
						case 't5567':$('#chpT5567').show('slow');break;
						case 'mifares501k':$('#chpmifare').show('slow');break;
						case 'icode2':$('#chpiCode2').show('slow');break;
						default: $('#rfd').show('slow');break;
					}
				}
		);
	$('#persdativariabili').click(function(){$('#cardHelp span').hide();$('#var').show('slow');});
	$('#persstampafoto').click(function(){$('#cardHelp span').hide();$('#fto').show('slow');});
	$('#colorifronte').click(function(){
		$('#cardHelp span').hide();
		if($('#colorifronte').val()=='mono'){$('#frn2').show('slow');}
		else if($('#colorifronte').val()=='quad'){$('#frn1').show('slow');}
		else $('#frn0').show('slow');
	});
	$('#coloriretro').click(function(){
		$('#cardHelp span').hide();
		if($('#coloriretro').val()=='mono'){$('#rtr2').show('slow');}
		else if($('#coloriretro').val()=='quad'){$('#rtr1').show('slow');}
		else $('#rtr0').show('slow');
	});
	$('#spessoreCard').click(function(){
		$('#cardHelp span').hide();
		if($('#spessoreCard').val()=='40'){$('#sps2').show('slow');}
		else if($('#spessoreCard').val()=='76'){$('#sps1').show('slow');}
		else $('#hlp').show();
	});
	$('#bandamagnetica').click(function(){
		$('#cardHelp span').hide();
		if($('#bandamagnetica').val()=='no')$('#bnd0').show('slow');
		else if($('#bandamagnetica').val()=='loco')$('#bnd1').show('slow');
		else $('#bnd2').show('slow');
	});
    $('#tipostampa').click(function(){
        $('#cardHelp span').hide();
        $('#tps').show('slow');
    });
	
    $('#costoCardQuantita').change(function(e) {checkTipoStampa();});
    $('#chipcontatto').change(function(e) {checkDoubleChip();});
    $('#chipcrfid').change(function(e) {checkDoubleChip();});
    $('#spessoreCard').change(function(e) {checkDoubleChip();});

	/*
	 * controllo login
	 */
	$('#quotation').click(function(){
		$('#domath').click();
		$('#costounitario').removeAttr("disabled");
		$('#costototale').removeAttr("disabled");
		$('#cardListCalculator').unbind('submit');
	});

	/*
	 * setup eventi per la preview
	 */
	$('#coloriretro').change(function(){preview();});
	$('#bandamagnetica').change(function(){preview();});
	$('#colorifronte').change(function(){preview();});
	$('#chipcontatto').change(function(){preview();});
	$('#chipcrfid').change(function(){preview();});
	$('#firma').change(function(){preview();});
	//$('#perscodicebarre').change(function(){preview();});
	$('#persdativariabili').change(function(){preview();});
	$('#punzonatura').change(function(){preview();});
	$('#persstampafoto').change(function(){preview();});
	$('#asolaturacard').change(function(){preview();});
	$('#tipostampa').change(function(){preview();checkTipoStampa();});
	$('#tipostampa').click(function(){preview();checkTipoStampa();});

	/*
	 * setup preview
	 */
	preview();

    if ( location.href.substr(-19) == 'card-quotation-send' ) {
        //setTimeout("$('#stepfour').click()", 5000);
        $('#stepfour').click();
    }
});

/*
 * funzione per le combo dati in preview
 */
function preview()
{

	// RETRO
	switch ($('#coloriretro').val()){
		case 'quad':
			$('#cpr').css('background-image', 'url(/images/card/quadricromia-[Convertito].png)');
			break;
		case 'mono':
			$('#cpr').css('background-image', 'url(/images/card/monocromia-[Convertito].png)');
			break;
		default:
			$('#cpr').css('background-image', 'url(/images/card/blank-[Convertito].png)');
			break;
	}

	// FRONTE
	switch ($('#colorifronte').val()){
		case 'quad':
			$('#cpf').css('background-image', 'url(/images/card/quadricromia-[Convertito].png)');
			break;
		case 'mono':
			$('#cpf').css('background-image', 'url(/images/card/monocromia-[Convertito].png)');
			break;
		default:
			$('#cpf').css('background-image', 'url(/images/card/blank-[Convertito].png)');
			break;
	}

	$('.data').hide();
	$('.barc').hide();
	switch ($('#persdativariabili').val()){
		case 'fronte':
			$('#cpf .data').show();
			$('#cpf .barc').show();
			break;
		case 'retro':
			$('#cpr .data').show();
			$('#cpr .barc').show();
			break;
		case 'ambo':
			$('.data').show();
			$('.barc').show();
			break;
	}

	switch ($('#persstampafoto').val()){
		case 'no':
			$('.foto').hide();
			break;
		case 'fronte':
			$('#cpf .foto').show();
			$('#cpr .foto').hide();
			break;
		case 'retro':
			$('#cpf .foto').hide();
			$('#cpr .foto').show();
			break;
	}

	switch ($('#bandamagnetica').val()){
		case 'hico':
			$('#cpr .banh').show();
			$('#cpr .banl').hide();
			break;
		case 'loco':
			$('#cpr .banh').hide();
			$('#cpr .banl').show();
			break;
		default:
			$('#cpr .banh').hide();
			$('#cpr .banl').hide();
	}

	$('#cpf .AT24C04').hide();
	$('#cpf .SLE4428').hide();
	$('#cpf .SLE4442').hide();
	$('#cpf .SLE5542').hide();
	$('#cpf .chip').hide();
	if ($('#chipcontatto').val() != 'no'){
		switch ($('#chipcontatto').val()){
			case 'at24c04':
				$('#cpf .AT24C04').show();
				break;
			case 'sle4428':
				$('#cpf .SLE4428').show();
				break;
			case 'sle4442':
				$('#cpf .SLE4442').show();
				break;
			case 'sle5542':
				$('#cpf .SLE5542').show();
				break;
			default:
				$('#cpf .chip').show();
		}
	} else if ($('#chipcrfid').val() != 'no') $('.chip').show();

	if ($('#firma').attr('checked')) $('#cpr .firm').show();
	else $('#cpr .firm').hide();

	if ($('#punzonatura').attr('checked')) $('.punz').show();
	else $('.punz').hide();

	if ($('#asolaturacard').attr('checked')) $('.asol').show();
	else $('.asol').hide();
}//**

/*
 * getValues x calcolo ajax
 */
function getFormValues(){
	var card = {};
	card.costoCardQuantita = 	$('#costoCardQuantita').val();
	card.spessoreCard = 		$('#spessoreCard').val();
	card.colorifronte = 		$('#colorifronte').val();
	card.coloriretro = 			$('#coloriretro').val();
	card.tipostampa = 			$('#tipostampa').val();
	
	card.bandamagnetica = 		$('#bandamagnetica').val();
	card.chipcontatto = 		$('#chipcontatto').val();
	card.chipcrfid = 			$('#chipcrfid').val();
	card.firma = 				$('#firma').attr('checked') ? 'true' : 'false';
	card.coloreserigrafico = 	$('#coloreserigrafico').attr('checked') ? 'true' : 'false';
	card.stampaacaldo = 	    $('#stampaacaldo').attr('checked') ? 'true' : 'false';
	card.asolaturacard = 		$('#asolaturacard').attr('checked') ? 'true' : 'false';
	
	card.persdativariabili = 	$('#persdativariabili').val();
	card.persstampafoto = 		$('#persstampafoto').val();
	card.punzonatura = 			$('#punzonatura').attr('checked') ? 'true' : 'false';
	card.codificamagnetica = 	$('#codificamagnetica').attr('checked') ? 'true' : 'false';
	card.codificadatichip = 	$('#codificadatichip').attr('checked') ? 'true' : 'false';
	card.foto =                 $('#foto').val();

	card.nomeprogettocard = 	$('#nomeprogettocard').val();
	card.note = 				$('#note').val();
	//card.perscodicebarre = 		$('#perscodicebarre').val();


	return card;
}//***

/*
 * funzione di controllo qty <-> tipostampa
 */
function checkTipoStampa(){
	$('#costounitario').val('');
	$('#costototale').val('');

    var quantita = $('#costoCardQuantita').val();
    $('option[value=off]').attr('disabled', '');
	$('#tipostampa option').removeAttr('disabled');

    var digits = new RegExp('^[0-9]+$');

    if (quantita == "" || digits.test($('#costoCardQuantita').val()) == false) {
        return;
    } else if (quantita > 999) {
        if ($('#tipostampa').val() != 'off') {
            if ( location.hostname.substr(-3) == '.it' ) alert("Per quantità superiori ai 1000 pezzi si deve usare la stampa in offset");
            else alert("For quantities over 1000 pieces you need to use offset printing");
            
            $('option[value=dir], option[value=ind]').attr('disabled', 'disabled');
            $('#tipostampa').val('off');
        }
    } else {
        if ($('#tipostampa').val() == 'off') {
            if ( location.hostname.substr(-3) == '.it' ) alert("Per quantità inferiori ai 1000 pezzi non si può usare la stampa in offset");
            else alert("For quantities less than 1000 items you can not use offset printing");

            $('option[value=off]').attr('disabled', 'disabled');
            $('#tipostampa').val('dir');
        }
    }//*****

    $('#cardHelp span').hide();
    $('#qty').show();
}//***

function checkDoubleChip(){
    
    var a = $('#chipcontatto').val();
    var b = $('#chipcrfid').val();
    var c = $('#spessoreCard').val();
    var locale = location.hostname.substr(-3) == '.it' ? 'it' : 'en';
    
    if (c == '40' && (a != 'no' || b != 'no')) {
        switch (locale){
            case 'it':
                alert("\r\nLo spessore di 0,40mm non supporta i chip, utilizzare lo spessore 0,76mm.\r\nHo provveduto a correggere lo spessore!");
                break;
            case 'en':
                alert("\r\nThickness 0,40mm don't allow the use of a chip, you must use thickness 0,76mm.\r\nThickness updated to 0,76mm!");
                break;
        }// switch
        $('#spessoreCard').val('76');
        return false;
    }// if

    if ( a != 'no' && b != 'no') {
        switch (locale){
            case 'it':
                alert("\r\nPer tessere ibride con doppio chip si prega di richiedere il preventivo.");
                break;
            case 'en':
                alert("\r\nAbout hybrid dual chip please request a quote.");
                break;
        }// switch
        $('#chipcontatto').val('no');
        $('#chipcrfid').val('no');
        return false;
    } else return true;
}// function


function checkSteps(){
    
    checkTipoStampa();
    checkDoubleChip();
    
    var digits = new RegExp('^[0-9]+$');
    var valid = true;
    var msg = '';
    var locale = location.hostname.substr(-3) == '.it' ? 'it' : 'en';
    
    if ( digits.test( $('#costoCardQuantita').val() ) ) valid = valid && true;
    else {
        valid = false;
        switch (locale){
            case 'it':
                msg += "\r\nPerfavore come quantita inserisci il numero in forma decimale.";
                break;
            case 'en':
                msg += "\r\nPleae as quantity use the decimal format.";
                break;
        }
    }
    
    if ( $('#costoCardQuantita').val() > 99 ) valid = valid && true;
    else {
        valid = false;
        switch (locale){
        case 'it':
            msg += "\r\nLa quantità minima per fare un ordine è di 100 pezzi.";
            break;
        case 'en':
            msg += "\r\nThe minimum amount for an order is 100 pieces.";
            break;
        }
    }
    
    return valid == true ? true : msg;
}


function gotoStep(N){
    switch(N){
    case 'four':
        $('#end-card-text-wrapper-open').hide();
        
        $('#wizard_one').attr('src', '/images/fourstep_one_off.jpg');
        $('#wizard_two').attr('src', '/images/fourstep_two_off.jpg');
        $('#wizard_three').attr('src', '/images/fourstep_three_off.jpg');
        $('#wizard_four').attr('src', '/images/fourstep_four_off.jpg');
        
        $('#mago_one-two').attr('src', '/images/fourstep_mago_gray.png');
        $('#mago_two-three').attr('src', '/images/fourstep_mago_gray.png');
        $('#mago_three-four').attr('src', '/images/fourstep_mago_gray.png');
        
        $('#mago_one-two').css('visibility', 'visible');
        $('#mago_two-three').css('visibility', 'visible');
        $('#mago_three-four').css('visibility', 'visible');
        
        $('fieldset', '#cardListCalculator').animate({
            opacity: 0
        }, 1000, 'linear', function() {
            $('#fieldset-base').css('display', 'none');
            $('#fieldset-opzioni').css('display', 'none');
            $('#fieldset-personalizzazioni').css('display', 'none');
            $('#fieldset-calc').css('display', 'block');
            $('#fieldset-askquotation').css('display', 'block');
            $('#fieldset-calc, #fieldset-askquotation').animate({
                opacity: 1
            }, 1000, 'linear', function(){});
        });
        break;
    case 'three':
        $('#end-card-text-wrapper-open').show();
        
        $('#wizard_one').attr('src', '/images/fourstep_one_on.jpg');
        $('#wizard_two').attr('src', '/images/fourstep_two_on.jpg');
        $('#wizard_three').attr('src', '/images/fourstep_three_on.jpg');
        $('#wizard_four').attr('src', '/images/fourstep_four_onto.jpg');
        
        $('#mago_one-two').attr('src', '/images/fourstep_mago_color.png');
        $('#mago_two-three').attr('src', '/images/fourstep_mago_color.png');
        $('#mago_three-four').attr('src', '/images/fourstep_mago_color.png');
        
        $('#mago_one-two').css('visibility', 'hidden');
        $('#mago_two-three').css('visibility', 'hidden');
        $('#mago_three-four').css('visibility', 'visible');
        
        $('fieldset', '#cardListCalculator').animate({
            opacity: 0
        }, 1000, 'linear', function() {
            $('#fieldset-base').css('display', 'none');
            $('#fieldset-opzioni').css('display', 'none');
            $('#fieldset-personalizzazioni').css('display', 'block');
            $('#fieldset-calc').css('display', 'none');
            $('#fieldset-askquotation').css('display', 'none');
            $('#fieldset-personalizzazioni').animate({
                opacity: 1
            }, 1000, 'linear', function(){});
        });
        break;
    case 'two':
        $('#end-card-text-wrapper-open').show();
        
        $('#wizard_one').attr('src', '/images/fourstep_one_on.jpg');
        $('#wizard_two').attr('src', '/images/fourstep_two_on.jpg');
        $('#wizard_three').attr('src', '/images/fourstep_three_onto.jpg');
        $('#wizard_four').attr('src', '/images/fourstep_four_onto.jpg');
        
        $('#mago_one-two').attr('src', '/images/fourstep_mago_color.png');
        $('#mago_two-three').attr('src', '/images/fourstep_mago_color.png');
        $('#mago_three-four').attr('src', '/images/fourstep_mago_color.png');
        
        $('#mago_one-two').css('visibility', 'hidden');
        $('#mago_two-three').css('visibility', 'visible');
        $('#mago_three-four').css('visibility', 'hidden');
        
        $('fieldset', '#cardListCalculator').animate({
            opacity: 0
        }, 1000, 'linear', function() {
            $('#fieldset-base').css('display', 'none');
            $('#fieldset-opzioni').css('display', 'block');
            $('#fieldset-personalizzazioni').css('display', 'none');
            $('#fieldset-calc').css('display', 'none');
            $('#fieldset-askquotation').css('display', 'none');
            $('#fieldset-opzioni').animate({
                opacity: 1
            }, 1000, 'linear', function(){});
        });
        break;
    case 'one':
    default:
        $('#end-card-text-wrapper-open').show();
    
        $('#wizard_one').attr('src', '/images/fourstep_one_on.jpg');
        $('#wizard_two').attr('src', '/images/fourstep_two_onto.jpg');
        $('#wizard_three').attr('src', '/images/fourstep_three_onto.jpg');
        $('#wizard_four').attr('src', '/images/fourstep_four_onto.jpg');
        
        $('#mago_one-two').attr('src', '/images/fourstep_mago_color.png');
        $('#mago_two-three').attr('src', '/images/fourstep_mago_color.png');
        $('#mago_three-four').attr('src', '/images/fourstep_mago_color.png');
        
        $('#mago_one-two').css('visibility', 'visible');
        $('#mago_two-three').css('visibility', 'hidden');
        $('#mago_three-four').css('visibility', 'hidden');
        
        $('fieldset', '#cardListCalculator').animate({
            opacity: 0
        }, 1000, 'linear', function() {
            $('#fieldset-base').css('display', 'block');
            $('#fieldset-opzioni').css('display', 'none');
            $('#fieldset-personalizzazioni').css('display', 'none');
            $('#fieldset-calc').css('display', 'none');
            $('#fieldset-askquotation').css('display', 'none');
            $('#fieldset-base').animate({
                opacity: 1
            }, 1000, 'linear', function(){});
        });
        break;
    }
    /*
    $('#wizard_one, #wizard_two, #wizard_three, #wizard_four').animate({opacity: 0, filter: 'Alpha(Opacity=0)'}, 500, 'easeInExpo', function(){
        //$('#wizard_'+N).css('display', 'block');
        $('#wizard_'+N).animate({opacity: 1, filter: 'Alpha(Opacity=100)'}, 500, 'easeOutExpo', function(){;});
    });
    */
}




















