$(document).ready(function() {

    /**************************************************************************/
    /*                        RICERCA PER COSTRUTTORE                         */
    /**************************************************************************/

    //carica i dati recuperati dal cookie se ce ne sono
    if ($('#dettVeic_form_costr').val() != '' && $('#dettVeic_form_model').val() != '' &&
        $('#dettVeic_form_id').val() != '' && $('#dettVeic_form_fami').val() != '') {
        setdettVeicFromCoockie();
    }

    //carica i modelli dei costruttori
    $('#dettVeic_form select[name="costr"]').bind('change', function() {
        removeVeicTable();
        loaddettVeicModel($(this).val());
    });

    //carica le versioni dei modelli
    $('#dettVeic_form select[name="model"]').bind('change', function() {
        removeVeicTable();
        loaddettVeicId('', $(this).val());
    });

    //controlla il form
    $('#dettVeic_form').bind('submit', function() {
        return validatedettVeic();
    });

    /**************************************************************************/
    /*                 RICERCA PER CODICE KBA (SOLO GERMANIA)                 */
    /**************************************************************************/

    //controlla il form
    $('#kba_form').bind('submit', function() {
        return validatekba();
    });

    /**************************************************************************/
    /*                      RICERCA PER CODICE ARTICOLO                       */
    /**************************************************************************/

    //controlla il form
    $('#articolo_form').bind('submit', function() {
        return validatearticolo();
    });

    /**************************************************************************/
    /*                       RICERCA PER CODICE MOTORE                        */
    /**************************************************************************/

    if ($('#dettMot_form_mcostr').val() != '' && $('#dettMot_form_id').val() != '') {
        setdettMot1($('#dettMot_form_mcostr').val(), $('#dettMot_form_id').val());
    }

    //carica le versioni dei modelli
    $('#dettMot_form select[name="mcostr"]').bind('change', function() {
        setdettMot1($(this).val(), '');
    });

    //controlla il form dettMot
    $('#dettMot_form input[name="dettMot_form_submit_1"]').bind('click', function() {
        return validatedettMot1();
    });
    $('#dettMot_form input[name="dettMot_form_submit_2"]').bind('click', function() {
        return validatedettMot2();
    });

    
    
    
    
    
    // selezione della versione dalla tabella delle versioni
    $('#myVersioni > td > table > tbody > tr').live('click', function(){
        var id = $(this).attr('id');
        //var versione = $($('td', this)[0]).text() + '/' + $($('td', this)[1]).text() + '/' + $($('td', this)[2]).text() + '/' + $($('td', this)[3]).text();
        //$('#myVersioni > td > table > tbody > tr').toggleClass('myBold', false); // rimuovo il grassetto dal testo di tutte le righe
        $('#myVersioni > td > table > tbody > tr').toggleClass('flagged', false);
        //$(this).toggleClass('myBold'); // imposto il grassetto per il testo della riga selezionata
        $(this).toggleClass('flagged'); 
        $('#myVersioni > td > table > tbody > tr > td.last').html('&nbsp;'); // rimuovo il flag da tutte le righe
        $('td.last', this).html('<img src="images/myFlag.png" alt="flag"/>'); // imposto il flag per la riga selezionata
        $('#dettVeic_form_id').val(id);
        //$('#myVersioni').toggleClass('myVisible');              
});

});

/******************************************************************************/
/*                          RICERCA PER COSTRUTTORE                           */
/******************************************************************************/

function setdettVeicFromCoockie() {
    var costr = $('#dettVeic_form_costr').val();
    var model = $('#dettVeic_form_model').val();
    var id = $('#dettVeic_form_id').val();
    var html = '', value = '', selected = '';
    var myJsp1, myJsp2;
    var myUrl = document.URL.toString();
    if (myUrl.indexOf("area_riservata") != -1) {
        myJsp1 = '../pezzi/xmlmodelli.jsp';
        myJsp2 = '../pezzi/xmlversioni.jsp';
    }
    else {
        myJsp1 = 'pezzi/xmlmodelli.jsp';
        myJsp2 = 'pezzi/xmlversioni.jsp';
    }
    //$.post('pezzi/xmlmodelli.jsp', {costr: costr}, function(xml) {
    $.post(myJsp1, {costr: costr}, function(xml) {
        $('modello', xml).each(function() {
            value = $('value', this).text();
            selected = model == value ? ' selected ' : '';
            html += '<option value="' + value + '"' + selected + '>';
            html +=     $('descr', this).text();
            html += '</option>';
        });
        $('#dettVeic_form select[name="model"]').html(html);
        html = '';
        //$.post('pezzi/xmlversioni.jsp', {model: model}, function(xml) {
        /*$.post(myJsp2, {model: model}, function(xml) {
            html += '<option value="0">' + $('#dettVeic_form_tutti').val() + '</option>';
            $('versione', xml).each(function() {
                value = $('value', this).text();
                selected = id == value ? ' selected ' : '';
                html += '<option value="' + value + '"' + selected + '>';
                html +=     $('descr', this).text();
                html += '</option>';
            });
            $('#dettVeic_form select[name="id"]').html(html);*/
            //resetta i dati recuperati dal cookie ed elimina il cookie stesso
            $('#dettVeic_form_costr').val('');
            $('#dettVeic_form_model').val('');
            $('#dettVeic_form_id').val('');
            $('#dettVeic_form_fami').val('');
            $.cookie('japan_ricerca', null);
        //});*/
        loaddettVeicId(id, model);
        });
    //});
}

function removeVeicTable() {
   $('#dettVeic_form_id').val('0');
   $('#myVersioni > td > table > tbody').empty();
   $('#myVersioni').toggleClass('myVisible', true);  
}

function loaddettVeicModel(costr) {
    var html = '<option value="">' + $('#dettVeic_form_scegli2').val() + '</option>';
    if (costr != '') {
        //showLoading();
        $.post('pezzi/xmlmodelli.jsp', {costr: costr}, function(xml) {
            $('modello', xml).each(function() {
                html += '<option value="' + $('value', this).text() + '">';
                html +=      $('descr', this).text();
                html += '</option>';
            });
            $('#dettVeic_form select[name="model"]').html(html);
            loaddettVeicId('', $('#dettVeic_form select[name="model"]').val());
            //hideLoading();
        });
    } else {
        $('#dettVeic_form select[name="model"]').html(html);
        html = '<option value="">' + $('#dettVeic_form_scegli3').val() + '</option>';
        //$('#dettVeic_form select[name="id"]').html(html);
    }
}

function loaddettVeicId2(model) {
    var html = '';
    if (model != '') {
        var myJsp;
        var myUrl = document.URL.toString();
        if (myUrl.indexOf("area_riservata") != -1) {
            myJsp = '../pezzi/versioni.jsp';
        }
        else {
            myJsp = 'pezzi/xmlversioni.jsp';
        }
        //$.post('pezzi/xmlversioni.jsp', {model: model}, function(xml) {
        $.post(myJsp, {model: model}, function(xml) {
            html += '<option value="0">' + $('#dettVeic_form_tutti').val() + '</option>';
            $('versione', xml).each(function() {
                html += '<option value="' + $('value', this).text() + '">' +
                $('descr', this).text() +
                '</option>';
            });
            $('#dettVeic_form select[name="id"]').html(html);
            //hideLoading();
        });
    } else {
        html = '<option value="">' + $('#dettVeic_form_scegli3').val() + '</option>';
        $('#dettVeic_form select[name="id"]').html(html);
    }
}

function loaddettVeicId(id, model) {
    var html = '';
    if (model != '') {
        //showLoading(); // mostra lo spinner ajax
        var myJsp;
        var myUrl = document.URL.toString();
        if (myUrl.indexOf("area_riservata") != -1) {
            myJsp = '../pezzi/xmlversioni.jsp';
        }
        else {
            myJsp = 'pezzi/xmlversioni.jsp';
        }
        $.post(myJsp, {model: model}, function(xml) {
            /*if ($('versione', xml).length > 1) {*/
                // sono presenti più versioni
                // costruisco la tabella
                $('versione', xml).each(function() {
                    html += '<tr id="' + $('value', this).text() + '"';
                    if (id == $('value', this).text()) {
                        html += ' class="flagged" ';                        
                    }
                    html +='><td>' + $('descr', this).text().split('/')[0] + '</td><td>' + $('descr', this).text().split('/')[1] + '</td><td>' + $('descr', this).text().split('/')[2] + '</td><td>' + $('descr', this).text().split('/')[3] + '</td><td width="10%" class="last">'; 
                    if (id == $('value', this).text()) {
                        html += '<img src="images/myFlag.png" alt="flag"/>';
                        $('#dettVeic_form_id').val(id);
                    }
                    else {                        
                        html += '&nbsp;';
                    }
                    html += '</td></tr>';
                });
                $('#myVersioni > td > table > tbody').append(html);
                // visualizzo la tabella
                $('#myVersioni').toggleClass('myVisible');
                $('#myVersioni > td > table').mouseleave();
            //}
            if ($('versione', xml).length == 1) {
                $('#myVersioni > td > table > tbody > tr').click();
                //$('#myVersioni > td > table').mouseleave();
            }
            /*else {
                // è presente un'univa versione: visualizzo la select classica
                //html += '<option value="0">' + $('#dettVeic_form_tutti').val() + '</option>';
                $('versione', xml).each(function() {
                    html += '<option value="' + $('value', this).text() + '">' + $('descr', this).text() + '</option>';
                });
                $('#dettVeic_form select[name="id"]').html(html);
            }*/
            //hideLoading();
        });
    } /*else {
        html = '<option value="">' + $('#dettVeic_form_scegli3').val() + '</option>';
        $('#dettVeic_form select[name="id"]').html(html);
    }*/
}

function validatedettVeic() {
    //showLoading();
    var err = '';
    var isok = true;
    if ($('#dettVeic_form select[name="costr"]').val() == '') {
        if ($('#input-lang').val() == '7') {
            err = 'Selezionare un costruttore';
        } else  {
            err = 'Select a manufacturer';
        }
        isok = false;
    }
    if (isok && $('#dettVeic_form select[name="model"]').val() == '') {
        if ($('#input-lang').val() == '7') {
            err = 'Selezionare un modello';
        } else  {
            err = 'Select a model';
        }
        isok = false;
    }
    if (isok && $('#dettVeic_form_id').val() == '0') {
        if ($('#input-lang').val() == '7') {
            err = 'Selezionare una versione';
        } else  {
            err = 'Select a version';
        }
        isok = false;
    }
    if (!isok) {
        //hideLoading();
        alert(err);
    } else {
        //crea il coockie
        var dati = 'dettVeic_form|';
        dati += $('#dettVeic_form select[name="costr"]').val() + '|';
        dati += $('#dettVeic_form select[name="model"]').val() + '|';
        //dati += $('#dettVeic_form select[name="id"]').val() + '|';
        dati += $('#dettVeic_form_id').val() + '|';
        dati += $('#dettVeic_form select[name="fami"]').val();
        $.cookie('japan_ricerca', dati, {path: '/'});
    }
    return isok;
}

/******************************************************************************/
/*                   RICERCA PER CODICE KBA (SOLO GERMANIA)                   */
/******************************************************************************/

function validatekba() {
    //showLoading();
    var err = '';
    var isok = true;
    if (isNaN($('#kba_form input[name="kba"]').val())) {
        if ($('#input-lang').val() == '7') {
            err = 'Il codice KBA deve essere un numero';
        } else  {
            err = 'KBA code must be a number';
        }
        isok = false;
    }
    if (isok && $('#kba_form input[name="kba"]').val().length < 2) {
        if ($('#input-lang').val() == '7') {
            err = 'Scrivere un codice KBA di almeno due caratteri';
        } else  {
            err = 'KBA code must be long at least two characters';
        }
        isok = false;
    }
    if (!isok) {
        //hideLoading();
        alert(err);
    } else {
        //crea il coockie
        var dati = 'kba_form|';
        dati += $('#kba_form input[name="kba"]').val() + '|';
        dati += $('#kba_form select[name="fami"]').val();
        $.cookie('japan_ricerca', dati, {path: '/'});
    }
    return isok;
}

/******************************************************************************/
/*                        RICERCA PER CODICE ARTICOLO                         */
/******************************************************************************/

function validatearticolo() {
    //showLoading();
    var err = '';
    var isok = true;
    if ($('#articolo_form select[name="tipoc"]').val() == 'nessuno') {
        if ($('#input-lang').val() == '7') {
            err = 'Scegliere un tipo di codice';
        } else  {
            err = 'Choose a type of code';
        }
        isok = false;
    }
    /*if (isok && $('#articolo_form input[name="codi"]').val() == '') {
        if ($('#input-lang').val() == '7') {
            err = 'Inserire un codice';
        } else  {
            err = 'Enter code';
        }
        isok = false;
    }*/
    if (!isok) {
        //hideLoading();
        alert(err);
    } else {
        //crea il coockie
        var dati = 'articolo_form|';
        dati += $('#articolo_form select[name="tipoc"]').val() + '|';
        dati += $('#articolo_form input[name="codi"]').val();
        $.cookie('japan_ricerca', dati, {path: '/'});
    }
    return isok;
}

/******************************************************************************/
/*                         RICERCA PER CODICE MOTORE                          */
/******************************************************************************/

function validatedettMot1() {
    //showLoading();
    var err = '';
    var isok = true;
    if ($('#dettMot_form select[name="mcostr"]').val() == '') {
        if ($('#input-lang').val() == '7') {
            err = 'Selezionare un costruttore';
        } else  {
            err = 'Select a manufacturer';
        }
        isok = false;
    }
    if (isok && $('#dettMot_form select[name="id"]').val() == '') {
        if ($('#input-lang').val() == '7') {
            err = 'Selezionare un codice motore';
        } else  {
            err = 'Select an engine code';
        }
        isok = false;
    }
    if (!isok) {
        //hideLoading();
        alert(err);
    } else {
        //crea il coockie
        var dati = 'dettMot_form|dettMot_form_submit_1|';
        dati += $('#dettMot_form select[name="mcostr"]').val() + '|';
        dati += $('#dettMot_form select[name="id"]').val();
        $.cookie('japan_ricerca', dati, {path: '/'});
    }
    return isok;
}

function validatedettMot2() {
    //showLoading();
    var isok = true;
    if ($('#dettMot_form input[name="mcode"]').val().length < 2) {
        //hideLoading();
        if ($('#input-lang').val() == '7') {
            alert('Scrivere un codice motore');
        } else  {
            alert('Write code engine');
        }
        isok = false;
    }
    if (isok) {
        //crea il coockie
        var dati = 'dettMot_form|dettMot_form_submit_2|';
        dati += $('#dettMot_form input[name="mcode"]').val();
        $.cookie('japan_ricerca', dati, {path: '/'});
    }
    return isok;
}

function setdettMot1(mcostr, id) {
    var html = '';
    if (mcostr != '') {
        var myJsp;
        var myUrl = document.URL.toString();
        if (myUrl.indexOf("area_riservata") != -1) {
            myJsp = '../pezzi/xmlmotcodici.jsp';
        }
        else {
            myJsp = 'pezzi/xmlmotcodici.jsp';
        }
        //$.post('pezzi/xmlmotcodici.jsp', {mcostr: mcostr}, function(xml) {
        $.post(myJsp, {mcostr: mcostr}, function(xml) {
            var isok = false;
            var value = null, selected = null;
            $('codice', xml).each(function() {
                isok = true;
                value = $('value', this).text();
                selected = value == id ? ' selected ' : '';
                html += '<option value="' + value + '"' + selected + '>';
                html +=      $('descr', this).text();
                html += '</option>';
            });
            if (!isok) {
                html = '<option value="">' + $('#dettMot_form_scegli4').val() + '</option>';
            }
            $('#dettMot_form select[name="id"]').html(html);
        });
    } else {
        html = '<option value="">' + $('#dettMot_form_scegli4').val() + '</option>';
        $('#dettMot_form select[name="id"]').html(html);
    }
}


function go() {
	var oggi = new Date();
	var data = "";
	data+=oggi.getDate()<10?"0"+oggi.getDate()+"/":oggi.getDate()+"/";
	data+=oggi.getMonth()<9 ? "0"+(oggi.getMonth()+1)+"/" : (oggi.getMonth()+1)+"/";
	data+=oggi.getFullYear();

	//var w = document.getElementById("optcat").selectedIndex;
	//var catjs = document.getElementById("optcat").options[w].text;

	var header = "<html><head><title>Catalogo JapanParts</title><link href=\"stili.css\" rel=\"stylesheet\" type=\"text/css\" /></head><body>";
	var testata = "<table border=\"0\" align=\"right\"><tr><td><img id=\"imgprn\" src=\"img/document-print.gif\" border=\"0\" alt=\"stampa\" title=\"stampa\" style=\"cursor:pointer\" onclick=\"window.print(); window.close();\" /></td></tr></table>";
	//testata += "<table border=\"0\"><tr><td class=\"testo_tabella\" align=\"left\" valign=\"top\">"+data+"</td></tr>";
	//testata += "<tr><td class=\"testo_tabella\" align=\"left\" valign=\"top\">da data <%=datada.substring(6,8)%>/<%=datada.substring(4,6)%>/<%=datada.substring(0,4)%> a data <%=dataa.substring(6,8)%>/<%=dataa.substring(4,6)%>/<%=dataa.substring(0,4)%></td></tr></table>";
	//testata += "<table border=\"0\"><tr><td class=\"testo_tabella\" align=\"left\" valign=\"top\">Kategorie: "+catjs+"</td></tr></table><br /><br />";
	var footer = "</body></html>";

    var a = window.open('','','width=800,height=600,scrollbars=yes');
    a.document.open("text/html");
    a.document.write(header);
    a.document.write(testata);
    var newdiv = a.document.createElement('div');
    newdiv.setAttribute('id', 'masterdiv');
    newdiv.innerHTML = document.getElementById('masterdiv').innerHTML;

	if (navigator.appName=="Netscape")
    	alert("Dokument fertig.");

    var objects = a.document.getElementsByTagName("BODY");
    for(var no=0;no<objects.length;no++) {
		objects[no].appendChild(newdiv);
    }

    /*
	var objects = a.document.getElementById("masterdiv").getElementsByTagName("TABLE");
    for(var no=0;no<objects.length;no++) {
		objects[no].border = "1";

		var cols = objects[no].getElementsByTagName("TD");
		if (no>0) {
			for(var nu=0;nu<cols.length;nu++) {
				if (nu==0)
					cols[0].style.display = "none";
			}
		}
    }
    */

	var obcts = a.document.getElementsByTagName("IMG");
    for(no = 0; no < obcts.length; no++) {
		obcts[no].style.display = "none";
    }

    obcts = a.document.getElementsByTagName("SPAN");
    for(var nod=0;nod<obcts.length;nod++) {
      obcts[nod].style.display = "none";
    }

	a.document.getElementById("imgprn").style.display = "block";
	a.document.write(footer);
    a.document.close();
    if (window.focus) {a.focus()}
}
