var
    J = jQuery.noConflict(),
    notif_id = 1,
    pers_notif = 5,
    patch_colorbox = false
;

function get(id){
    return document.getElementById(id);
}

function log(a){
    if(debug)
        console.log(a);
}

function dialogText(content, titre) {
 return dialog(J("<p id='dialogText'>").html(content),titre);
}

function dialog(content, titre) {
    if(content.css("width") == "auto")
        var w = "400";
    else
        var w = content.css("width").substr(0, content.css("width").length - 2);
    w = (1*w) + 100;
    w = w +"px";
    var popup = J('#popup')
                    .clone()
                    .dialog({
                        bgiframe: true,
                        modal: true,
                        position: [50,10],
                        title: titre,
                        width: w,
                        maxWidth: "800px",
                        maxHeight: "400px",
            		    buttons: { "Fermer": function() { J(this).dialog("close"); } },
                        closeText: "Fermer"
//                        close: function () {J("#popup").html('');}
                    });
    content.appendTo(J(popup));
    content.show();
    return J(popup);
}

J(document).ready(function(){
    if(!controller) return;
    // change l'affichage des boutons
    styleButton();
    // defini onglet et autre pour la page
    setPage();
    //fonction de calcul d'un nouveau loyer
    J('#calculAug').click(function () {
        var l = J("#loyer").val().replace(",",".");
        var o = J("#old_indice").val().replace(",",".");
        var i = J("#indice").text().replace(",",".");
        if(isNaN(l) || isNaN(o) || isNaN(i) || l == "" || o == "") {
            notifie(1, 'Veuillez remplir les champs avec des chiffres.');
            return ;
        }
        var retour = Math.round(((l * i) / o)*100) / 100;
        dialogText("Informations fournies :<br />Loyer à la signature : " + l + " euros<br />Indice à la signature : " + o + "<br />Selon les renseignements fournis, <br />Le nouveau loyer est de " + retour + " euros.<br />", "Calcul de loyer");
    });
    // vide les inputs au chargement de la page
    J('.videInput').val('');
    //intitialisation des checkbox
    initCheckbox();
    //compteur
    if(controller == 'admin') {

    } else {
//        J('#compteur').hide();
    }

    // gestion des diag
    manageDiagnostic();

    if(get('input_energie')) {
		diagManuel();
    }

    if(get('history_back')) {
		J('#history_back')
			.click(function () {
				history.back();
			})
		;
    }

    if(get('photo_selector'))
        J('#photo_selector')
            .change(confirmPhoto);
});

function confirmPhoto() {
    return; //.
    if(J('#photo_selector').val() == '')
        return;
    getFormPhoto(J('#photo_selector').val(), J('#id').val())
        .appendTo(
        J('<div />')
            .attr('id', 'photo_preview')
            .css({
                position: 'absolute'
            })
            .appendTo(
                J('<div />')
                    .attr('id', 'overlay')
                    .click(function () {
                        J(this).remove();
                    })
                    .appendTo('body')
                    .fadeIn()
            )
        );
}

function getFormPhoto(path, id) {
    J('<iframe />')
        .attr('id', 'framePhoto')
        .attr('name', 'framePhoto')
        .appendTo('body')
    ;

    var form =
        J('<form />')
            .attr('method', 'post')
            .attr('action', '/vente/addPhoto')
            .attr('target', 'framePhoto')
        ;

    J('#photo_selector')
        .clone()
        .attr('id', '87sdff2')
        .attr('name', 'photo')
        .css('z-index', '1')
        .appendTo(form);

    J('<input />')
        .attr('type', 'hidden')
        .attr('name', 'id')
        .val(id)
        .appendTo(form);

    J('<input />')
        .attr('type', 'submit')
        .val('Confirmer')
        .appendTo(form);

    return form;
}

function patchCB() {
    patch_colorbox = true;
}

function setPage() {
    // set l'onglet
    J('#ong_' + controller).addClass('onglet_actif');

    //set la taille si erreurs recherche
    var h = J("#div_recherche dd ul.errors").size() * 42;
    if(h) {
        var start = J("#div_recherche").css('height');
        start = 1 * start.substr(0, start.length - 2)
        J("#div_recherche").css('height', h + start);
    }
    //set la taille si erreurs mandat
    var h = J("#mandat_proprio .ligne .errors").size() * 42;
    if(h) {
        var start = J("#content").css('height');
        start = 1 * start.substr(0, start.length - 2)
        J("#content").css('height', h + start);
    }
    J("#submit_form_estimation").css('bottom', 10 - h);
    if(controller == 'mandat') {
        J("#submit_form_mandat").css('bottom', 10 - h);
        var diff = J("#mandat_bien .ligne .errors").size() - J("#mandat_proprio .ligne .errors").size();
        if(diff>1) {
            diff = diff * 42;
            J("#content").css('height', h + start + diff);
            J("#submit_form_mandat").css('bottom', 10 - (h + diff));
        }
    }


     // on engage les onglets pour le service proprio
    if (controller == "proprietaire") {
        setOngletProprio();
        J("#link_indices").click(function () {
            var popup = dialog(J("#table_indices"), "Tableau des indices INSEE");
        });

    }
    // photo qui defilent
    if (controller == "vente" || controller == "location") {
        // place du zoom
        var side = controller == "vente" ? "left" : "right";
		J("#imgHover").css(side , "20px");
		J("#scroller").simplyScroll({autoMode: 'loop'});
		J(".imgSlide").click(function() {
    	    J('#zoom').html('');
            J(this)
                .clone()
                .css({
                    "width" : "580px",
                    "height" : "300px"
                })
		        .appendTo(J('#zoom'));
	        J("#zoom").show();
	        setTimeout(function () {J("#zoom").fadeOut("slow");}, 3000);
		});
    }
    // changement de theme si nécessaire
    if (controller == "vente" || controller == "vendre" || controller == "contact" || controller == "estimation" || controller == "mandat")
        J('body').addClass("t_rouge");
    if (controller == "vente")
		J("#bien").change(function () {
		    J("#form_vente").submit();
		});
//        initOngletVente();
    if (controller == "accueil")
        initFonduAccueil();

    initImgHover();

    J.each(J('label'), function () {
        if (J(this).attr("tag") == "")
            J(this).removeAttr("tag")
    });

}

function initCheckbox() {
    J('#cc_tous').click(function () {
        J('.cc_offre').attr('checked', J(this).attr('checked'));
    });
    J.each(J('.cc_offre'), function () {
        J(this).click(function () {
            var all = true;
            J.each(J('.cc_offre'), function () {
                if(!J(this).is(':checked')) {
                    all = false;
                    return ;
                }
            });
            J('#cc_tous').attr('checked', all);
        });
    });
}

function styleButton() {
    J.each(J('.styleButton'), function () {
        id = J(this).attr("id");
        if (id == 'submit_form_connect'){
            var cls = 'pti_button';
            var w = "80px";
        }
        else {
            var cls = 'button';
            var w = "160px";
        }
        J(this).attr("id", "orig_" + id)
        var fake = J("<a />")
            .attr("href", "#")
            .attr("id", id)
            .attr("class", J(this).attr("class"))
            .css({
                'text-decoration':'none',
                'width': w,
                'text-align':'center'
            })
            .click(function () {
                get("orig_" + J(this).attr('id')).click();
            })
            .appendTo(J(this).parent());
            J(this).hide();
        var div = J("<div />")
                    .addClass(cls)
                    .html("<p>" + J(this).attr("value") + "</p>")
                    .appendTo(fake);
    });
}

function setOngletProprio() {
    J.each(J("#divOngletProprio a"), function() {
        J(this).click(function () {
            var id = J(this).attr('id');
            J('div.proprietaire:visible').fadeOut("slow", function () {
                J("#div_" + id).fadeIn("slow");
                return false;
            });
        });
        J("#div_" + J(this).attr('id')).fadeOut("fast");
    });
    J("#div_pro_desc").fadeIn("slow");
}


function isDouble(x) {
    if(x.indexOf(',') === false)
        return !isNaN(x);

    var y = x.substr(0, x.indexOf(',')) + x.substr(x.indexOf(',')+1, x.length - x.indexOf(',')+1);
    if(y.indexOf(',') === false) {
        notifie(1, 'Une seule virgule est autorisée.')
        return false;
    }
    return !isNaN(y);
}

function diagManuel() {
	J('span.valeur_diag').css('margin-top', '10px');
	J('#input_energie, #input_ges').keyup(function () {
		J('#diag_energie_div').children('span.valeur_diag').html(J('#input_energie').val());
		J('#diag_ges_div').children('span.valeur_diag').html(J('#input_ges').val());
		manageDiagnostic();
	});
}

function manageDiagnostic() {
	J.each(J('.fleche_diag_div'), function () {
		var val = J(this).children('span.valeur_diag').html();
//			console.log(val);
//			console.log(isNaN(val));
		if(val != "" && !isNaN(val)) {
			if(J(this).attr('id').indexOf('energie') != -1) {
				var id = 'energie';
				var max = 590;
				var paliersU = [0, 50, 51, 90, 91, 150, 151, 230, 231, 330, 331, 450, 451, max];
			} else {
				var id = 'ges';
				var max = 100;
				var paliersU = [0, 5, 6, 10, 11, 20, 21, 35, 36, 55, 56, 80, 81, max];
			}
			var paliersPX = [-4, 17, 20, 41, 44, 65, 68, 88, 92, 113, 116, 136, 139, 160];
			var palier = paliersU.length - 2;
			for (var i = 0; i < paliersU.length; i = i + 2) {
				if(val < paliersU[i + 1]) {
					palier = i;
					break;
				}
			}
			if(val > max)
				val = max;
			var offset = ((paliersPX[palier + 1] - paliersPX[palier])
						  / (paliersU[palier + 1] - paliersU[palier]))
						  * (val - paliersU[palier])
						  + paliersPX[palier];
			J(this).css({
				top: offset + 'px' ,
				right: '50px'
			});

		} else {
			J(this).children('span.valeur_diag').html('N/C');
			J(this).css({
				right: '50px'
			});
		}
	});
}

function notifie(id, msg)
{
    var txt;
    switch (id)
    {
        case 0: case 'success':
            id = 'ui-state-highlight';
            txt = 'Information';
        break;
        case 1: case 'error':
            id = 'ui-state-error';
            txt = 'Erreur';
        break;
        case 2: case 'warning':
            id = 'ui-state-highlight';
            txt = 'Avertissement';
        break;
        case 3: case 'info':
            id = 'ui-state-highlight';
            txt = 'Information';
        break;
    }
    notif_id++;
    tmp_id = 'notif_' + notif_id;
    J('#notifications')
        .show()
        .append(
            J('<li />')
                .click(function(){ J(this).remove(); })
                .attr('id', tmp_id)
                .addClass(id)
                .addClass('ui-corner-all')
                .css('margin', '10px 20px')
                .css('cursor', 'pointer')
            .append(
                J('<p />')
                    .append(
                        J('<span />')
                            .addClass('ui-icon ui-icon-info')
                            .css('float', 'left')
                            .css('margin-right', '0.3em')
                    )
                    .append(
                        J('<strong />')
                            .text(txt)
                    )
                    .append(
                        J('<div />')
                            .html(msg)
                    )
            )
        );
        if(pers_notif != 0){
            setTimeout('J("#" + tmp_id).hide(1000)',pers_notif * 1000);
            setTimeout('J("#" + tmp_id).remove()',(pers_notif * 1000) + 1000);
        }
}


/* LINK 2 FORM */
function link2form(action, params)
{
    if(params['toGet'] == 'checked') {
        params.ids = getOffreSelected();
        if(!params.ids.length) {
            notifie(1, 'Veuillez sélectionner au moins une offre.')
            return ;
        }
    }
    var form = J('<form />')
        .attr('method', 'post')
        .attr('action', action)
        .hide()
        .appendTo('body');
    for (var i in params)
    {
        J('<input />')
            .attr('type', 'hidden')
            .attr('name', i)
            .attr('value', params[i])
            .appendTo(form);
    }
    form.submit();
}

function getOffreSelected(){
    var ids = [];
    J.each(J(".cc_offre"), function () {
        if(J(this).is(':checked')) {
            var id =  J(this).attr('id');
            ids.push(id.substring(6, id.length));
        }
    });
    return ids;
}

function initOngletVente() {
    J(".page_vente").hide();
    J("#a_vente_appartement").click(function () {
        J("#vente_maison").fadeOut("slow", function () {
            J("#vente_appartement").fadeIn("slow");
        });
    });
    J("#a_vente_maison").click(function () {
        J("#vente_appartement").fadeOut("slow", function () {
            J("#vente_maison").fadeIn("slow");
        });
    });
}

function initImgHover() {
    J.each(J('.photo_zoom'), function () {
        imgHover(J(this));
    });

}

function imgHover(selecteur) {
    J(selecteur).hover(function () {
        J("#imgHover").html("");
        J(selecteur)
            .clone()
            .removeClass('photo_zoom')
            .addClass('zoomed_photo')
            .appendTo(J("#imgHover"));
        J("#imgHover").fadeIn("fast");
    }, function () {
        J("#imgHover").hide();
    });
}

function initFonduAccueil () {
    J("#acc_txt").hide();
    J("#acc_img").hide();
    var content = J("#acc_txt").html();
    J("#acc_txt").html('');
    J("#acc_txt").slideToggle("slow", function () {
        J("#acc_img").fadeIn("slow");
        J("#acc_txt").html(content);
    });
}

function initFonduMention () {
    J("#mention").hide();
    J("#mention").slideToggle("slow");
}

function plur(val, str, plur)
{
    return val + ' ' + (val > 1 ? plur ? plur : str + 's' : str);
}

function a(){
    alert('ok');
}

function notifie(id, msg)
{
    var txt;
    switch (id)
    {
        case 0: case 'success':
            id = 'ui-state-highlight';
            txt = 'Info';
        break;
        case 1: case 'error':
            id = 'ui-state-error';
            txt = 'Erreur';
        break;
        case 2: case 'warning':
            id = 'ui-state-highlight';
            txt = 'Avertissement';
        break;
        case 3: case 'info':
            id = 'ui-state-highlight';
            txt = 'Info';
        break;
    }
    notif_id++;
    tmp_id = 'notif_' + notif_id;
    J('#notifications')
        .show()
        .append(
            J('<li />')
                .click(function(){ J(this).remove(); })
                .attr('id', tmp_id)
                .addClass(id)
                .addClass('ui-corner-all')
                .css('margin', '10px 20px')
                .css('cursor', 'pointer')
            .append(
                J('<p />')
                    .append(
                        J('<span />')
                            .addClass('ui-icon ui-icon-info')
                            .css('float', 'left')
                            .css('margin-right', '0.3em')
                    )
                    .append(
                        J('<strong />')
                            .text(txt)
                    )
                    .append(
                        J('<div />')
                            .html(msg)
                    )
            )
        );
    setTimeout('J("#" + tmp_id).hide(1000)',4000);
    setTimeout('J("#" + tmp_id).remove()',5000);
}

function callbackOffreDelete() {
    if(json.exe) {
        J('#offre_' + json.id).remove();
    }
}


function submitAjax(url, unique_id, params, successCallback)
{
    if(J.isArray(params)) alert('Tableau à passer en objet');//.
    successCallback = successCallback || successAjaxDefault;
    params = params || {};
    params.unique_id = unique_id;
    J.ajax({
        url: url,
        data: params,
        success: successCallback
    });
}
