/*--
#    Name    : wizard.js
#    Author  : Jerod Santo
#    Contact : "moc.liamg@otnas.dorej".reverse
#    Date    : 2008 August  9
#    About   : Provides wizard-esque web page for forms or whatever
#								To be used in conjunction with Cody Lindley's CSS Step Menu:
#								http://codylindley.com/CSS/325/css-step-menu
#							 Insipered by a similar implementation at:
#								http://worcesterwideweb.com/2007/06/04/jquery-wizard-plugin/
#--*/



$(document).ready(function () {

    $("#step_lingue h3[class='trigger active'] a").bind("click", function (event) {
        alert($(this).attr("id"));
    });


    // all content starts hidden
    $('.step_content').hide();
    $('#step_content').hide();
    // initialize the wizard state
    load_state(1);

    // loads new state based on button clicked
    $('.step_buttons a').click(function () {
        //reset the wizardcontent to hidden
        $('#step_content').hide();
        var current_state = $('#test').attr('class');
        //we only want the number, converted to an int
        current_state = parseInt(current_state.replace(/(step_)/, ""));
        //figure out if 'next' or 'previous' was clicked and load appropriate state
        if ($(this).attr('id') == 'next_step') { load_state(++current_state, "avanti"); }
        else if ($(this).attr('id') == 'previous_step') { load_state(--current_state, "indietro"); }
    });
});

function load_state(current_state, direzione) {
	//disable all buttons while loading the state
	$('#previous_step').css('visibility','hidden');
	$('#next_step').css("visibility","hidden");
    //load the content for this state into the wizard content div and fade in

	//TONY ADD
	if (current_state == 2) {
	    var lingOld = document.getElementById("lingua").value;
	    var lingNew = $("#step_lingue h3[class='trigger active']").attr("id");
	    if (lingNew == undefined || lingNew == "") lingNew = $("#step_content #step_lingue h3[class='trigger active']").attr("id");
	    var paramLingua = "0";
	    if (lingOld == "0") {
	        //primo accesso
	        paramLingua = lingNew;
	    }
	    else {
	        if (lingNew != undefined && lingOld != lingNew) paramLingua = lingNew;
	        else paramLingua = lingOld;
        }
        document.getElementById("lingua").value = paramLingua;
        var sezione = document.getElementById("sezione").value;
	    var categoria = document.getElementById("categoria").value;
	    var indirizzo = "/ajax/ajaxStudiaLavora.aspx?step=1&idsez=" + sezione + "&idcat=" + categoria + "&idlng=" + paramLingua;
	    $('#step_content').html('<table id="step_destinazioni"><tr><td>Ricerca in corso...</td></tr></table>');
	    $.ajax({
	        type: "GET",
	        url: indirizzo,
	        data: "{}",
	        contentType: "application/json; charset=utf-8",
	        dataType: "json",
	        success: function (msg) {
	            var conta = 0;
	            $("#step_content").show().html("");
	            var table = "<table id='step_destinazioni'>";
	            var temp = "";
	            $.each(msg, function (i, post) {
	                conta++;
	                var cittaH = citta = document.getElementById("citta").value;
	                if (cittaH == 0) {
	                    temp += '<td><input type="radio" name="a" id="' + post.ID + '"  /><label for="a">' + post.Titolo + '(' + post.Descrizione + ')' + '</label></td>';
	                }
	                else {
	                    if (cittaH == post.ID) {
	                        temp += '<td><input type="radio" name="a" id="' + post.ID + '" checked /><label for="a">' + post.Titolo + '(' + post.Descrizione + ')' + '</label></td>';
                        }
	                    else {
	                        temp += '<td><input type="radio" name="a" id="' + post.ID + '"  /><label for="a">' + post.Titolo + '(' + post.Descrizione + ')' + '</label></td>';
                        }
	                }
	                if (conta == 3) {
	                    //debugger;
	                    table += "<tr>";
	                    table += temp;
	                    table += "</tr>";
	                    temp = "";
	                    conta = 0;
	                }
	                if (i == msg.length - 1 && conta > 0 && conta < 3) {
	                    table += "<tr>";
	                    table += temp;
	                    if (conta == 1) table += "<td></td><td></td>";
	                    if (conta == 2) table += "<td></td>";
	                    table += "</tr>";
	                }
	            });
	            table += "</table>";
	            $('#step_content').show().html(table);
	        }
	    });

	}
	else if (current_state == 3) {
	    if (direzione == "avanti") {
            //prende i dati selezionati dello step precedente e li salva nell'hidden apposito
	        var citta = "0";
	        citta = $("#step_destinazioni input[name='a']:checked").attr("id");
	        if (citta == undefined) {
	            citta = document.getElementById("citta").value;
	        }
	        document.getElementById("citta").value = citta;
	        var content = $('#step_' + current_state).html();
	        $('#step_content').html(content);
	    }
	    else {
	        var content = $('#step_' + current_state).html();
	        $('#step_content').html(content);
	        var rimetti = 1;
	        var tipo = "0";
	        tipo = $("#step_content ul.tipologia input[name='a']:checked").attr("id");
	        if (tipo == undefined) {
	            tipo = document.getElementById("tipo").value;
	            var idradio = "tipo_" + tipo;
	            $("#step_content ul.tipologia input[id=" + idradio + "]").attr("checked", true);
	            rimetti = 0;
	        }
	        if (rimetti == 1) {
	            document.getElementById("tipo").value = tipo != 0 ? tipo.substr(5) : tipo;
	        }
        }
	}
	else if (current_state == 4) {
	    if (direzione == "avanti") {
	        //prende i dati selezionati dello step precedente e li salva nell'hidden apposito
	        var rimetti = 1;
	        var tipo = "0";
	        tipo = $("#step_content ul.tipologia input[name='a']:checked").attr("id");
	        if (tipo == undefined) {
	            tipo = document.getElementById("tipo").value;
	            rimetti = 0;
	        }
	        if (rimetti == 1) {
	            document.getElementById("tipo").value = tipo != 0 ? tipo.substr(5) : tipo;
	        }
	        var content = $('#step_' + current_state).html();
	        $('#step_content').html(content);
	    }
	    else {
	        var content = $('#step_' + current_state).html();
	        $('#step_content').html(content);
	        var sist = document.getElementById("sist").value;
	        var idradio = "sist_" + sist;
	        $("#step_content ul.tipologia input[id=" + idradio + "]").attr("checked", true);
	    }
	}
	else if (current_state == 5) {
	    if (direzione == "avanti") {
	        //prende i dati selezionati dello step precedente e li salva nell'hidden apposito
	        var rimetti = 1;
	        var sist = "0";
	        sist = $("#step_content ul.tipologia input[name='a']:checked").attr("id");
	        if (sist == undefined) {
	            sist = document.getElementById("sist").value;
	            rimetti = 0;
	        }
	        if (rimetti == 1) {
	            document.getElementById("sist").value = sist != 0 ? sist.substr(5) : sist;
	        }

	        var content = $('#step_' + current_state).html();
	        $('#step_content').html(content);
	    }
	}
	else {
	    var content = $('#step_' + current_state).html();
	    $('#step_content').html(content);
	}
    //END TONY ADD

	$('#step_content').fadeIn("slow");
    //set the wizard class to current state for next iteration
    $('#test').attr('class','step_'+ current_state);
    var iterator = 1;
    // the state heading h3. removing is no biggie
    // loop through the list items and set classes for css coloring
    $('#stepnav li').each(function () {
        var step = $(this)
        if (iterator == current_state) {
            step.attr('class', 'sprite current');
        }
        else if (current_state - iterator == 1) { step.attr('class', 'sprite lastDone'); }
        else if (current_state - iterator > 1) { step.attr('class', 'sprite done'); }
        else { step.attr('class', 'sprite'); }
        // special case for step 5 because it doesn't have bacground image

        iterator++;

        if (current_state == 1) {
            $("#step_content .step_lingue_content").hide(); //Hide all content
            $('#step_content .trigger:first').addClass('active').next().show();
            $('.trigger').click(function () {
                if ($(this).next().is(':hidden')) { //If immediate next container is closed...
                    $('.trigger').removeClass('active').next().hide(); //Remove all .acc_trigger classes and slide up the immediate next container
                    $(this).toggleClass('active').next().show(); //Add .acc_trigger class to clicked trigger and slide down the immediate next container
                }
                return false; //Prevent the browser jump to the link anchor
            });
        }
    });

    //depending on the state, enable the correct buttons
    switch (current_state) {
        case 1:
            $('#next_step').css('visibility', 'visible');
            document.getElementById("lingua").value = "0";
            document.getElementById("citta").value = "0";
            document.getElementById("tipo").value = "0";
            document.getElementById("sist").value = "0";
            break;
        default:
            $('#previous_step').css('visibility', 'visible');
            if (current_state == 4) { $('#next_step').html('Visualizza Risultati').css('visibility', 'visible'); }
            else { $('#next_step').html('Avanti >').css('visibility', 'visible'); }
            if (current_state == 5) {
                $('#next_step').css('visibility', 'hidden');
                //check_hidden_fields();
                get_results(0, 2);
            }
            else {
                $('#pager').html('');
            }
            break;
    } //end switch
}

function check_hidden_fields() {
    var msg = document.getElementById("sezione").value + "-" +
                          document.getElementById("categoria").value + "-" +
                          document.getElementById("lingua").value + "-" +
                          document.getElementById("citta").value + "-" +
                          document.getElementById("tipo").value + "-" +
                          document.getElementById("sist").value;
    alert(msg);
}

function get_results(start, count) {
    var idSez = document.getElementById("sezione").value;
    var idCat = document.getElementById("categoria").value;
    var idLing = document.getElementById("lingua").value;
    var isoCode = document.getElementById("citta").value;
    var idTipo = document.getElementById("tipo").value;
    var idSist = document.getElementById("sist").value;
    var indirizzo = "/ajax/ajaxStudiaLavora.aspx?step=5&idsez=" + idSez + "&idcat=" + idCat + "&idlng=" + idLing +
                                                        "&iso=" + isoCode + "&tipo=" + idTipo + "&sist=" + idSist +
                                                        "&ri=" + start + "&rs=" + count;
    $('#step_content').show().html("RICERCA IN CORSO...");
    $.ajax({
        type: "GET",
        url: indirizzo,
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var riepilogo = "";
            var prodotti = "<div id=\"prova\">";
            var totale = "";
            $.each(msg, function (i, prod) {
                if (prod.ID == "0") {
                    totale = prod.Immagine;
                    riepilogo = "<p class=\"risultati\">La ricerca ha prodotto <span>" + prod.Immagine + " Risultati</span></p>";
                }
                else {
                    prodotti += "<div class=\"step_risultati\">";
                    prodotti += "   <img src=\"" + prod.Immagine + "\" width=\"109\" height=\"109\" alt=\"destinazione\" />";
                    prodotti += "   <div>";
                    prodotti += "      <h3>" + prod.Titolo + "</h3>";
                    prodotti += "         <table>";
                    prodotti += "            <tr>";
                    prodotti += "               <td class=\"step_titoli\">Destinazione:</td> <td>" + prod.Destinazione + "</td></tr>";
                    prodotti += "            <tr>";
                    prodotti += "               <td class=\"step_titoli\">TIPOLOGIA:</td> <td>" + prod.Tipologia + "</td></tr>";
                    prodotti += "            <tr>";
                    prodotti += "               <td class=\"step_titoli\">SISTEMAZIONE:</td> <td>" + prod.Sistemazione + "</td></tr>";
                    prodotti += "         </table>";
                    prodotti += "         <p>" + prod.Descrizione;
                    prodotti += "         <a href=\"" + prod.Link + "\">Scopri di pi&ugrave;</a></p>";
                    prodotti += "   </div>";
                    prodotti += "</div>";
                }
            });
            var records = parseInt(totale);
            //alert(records + " " + records % 2 + " " + Math.floor(records / 2));
            var pagine = records % 2 == 0 ? Math.floor(records / 2) : Math.floor(records / 2) + 1;
            var script = "<script type=\"text/javascript\">";
            script += "$(\"#pager\").paginate({";
            script += "    count: " + pagine + ",";
            script += "    start: " + ((start / 2) + 1) + ","; //script += "    start: 1,";
            script += "    display: 2,";
            script += "    border: true,";
            script += "    border_color: '#fff',";
            script += "    text_color: '#fff',";
            script += "    background_color: 'black',";
            script += "    border_hover_color: '#ccc',";
            script += "    text_hover_color: '#000',";
            script += "    background_hover_color: '#fff',";
            script += "    images: false,";
            script += "    mouse: 'press',";
            script += "    onChange: function (page) {";
            script += "        $('._current', '#step_content').removeClass('_current').hide();";
            script += "        $('#p' + page).addClass('_current').show();";
            script += "    }";
            script += "});";
            script += "</script>";
            $('#step_content').show().html(riepilogo + prodotti + script);

        }
    });
}

function substGraves(originalText) {
    var newText = originalText.replace("ù", "&ugrave;");
    return newText;
}
