//KISS & DRY please
$(document).ready(function() {
    addStuff();
    hoverTitle();
    if (typeof (Shadowbox) != "undefined") {
        $("a[rel*=shadowbox]").live("click", function() { Shadowbox.open(this, { animate: false }); return false; })
    } else {
    }
});

function addStuff() {
    // Ajouter Ã  ...
    $(".dropdown_fake .select_fake_title, .dropdown_fake ul, .dropdown_fake .select_fake_add").hover(function() {
        $(this).parent().find("ul").addClass("hover");
    }, function() {
        $(this).parent().find("ul").removeClass("hover");
    });

    $(".box_histfav ul li.tab_favoris, .box_histfav ul li.tab_favoris ul").hover(function() {
        $(this).find("ol").addClass("hover");
    }, function() {
        $(this).find("ol").removeClass("hover");
    });

    $(".box_tooltip").html("");
    $(".box_tooltip").append('<div class="tooltipBody"></div>')
    $(".box_tooltip").append('<div class="tooltipFoot"></div>')
    $(".tooltip").hover(function(e) {
        $(".box_tooltip .tooltipBody").html($(this).text());
        $($(this)).mousemove(function(e) {
            $(".box_tooltip").css("left", e.pageX - 15);
            $(".box_tooltip").css("top", e.pageY - ($(".box_tooltip").outerHeight(true) + 7));
        });
        $(".box_tooltip").css("display", "block");
    }, function() {
        $(".box_tooltip").css("display", "none");
    });
}

var fieldCompare = {
    active: false,
    timeout: 0,
    activeTab: null,
    fields: {}
};
function checkFields(id) {
    var txt = $("#" + id + " input[type='text']").val(), _id = id;
    if (txt.length > 1 && typeof (fieldCompare.fields[fieldCompare.activeTab]) != "undefined" && txt != fieldCompare.fields[fieldCompare.activeTab]) {
        clearTimeout(fieldCompare.timeout);

        //sends ajax request 
        handleAjax(txt, _id, function() { checkFields(_id) });
        //console.log("modified -> ajax check -"+txt+"-"+fieldCompare.fields[fieldCompare.activeTab])
    } else {
        //console.log("same -> loop this checkfield fx")
        fieldCompare.timeout = setTimeout(function() {
            checkFields(_id)
        }, 500);
    }
    fieldCompare.fields[id] = txt;
}
function changeTab(element, tabid) {
    clearTimeout(fieldCompare.timeout);
    //de/activate field comparison -> ajax requests
    if (tabid === "crit_studio_tab" || tabid === "crit_agency_tab" || tabid === "crit_brand_tab") {
        fieldCompare.active = true;
        fieldCompare.activeTab = tabid;
        checkFields(tabid);
    } else {
        fieldCompare.activeTab = null;
        clearTimeout(fieldCompare.timeout);
    }
    /*show-hide old crap*/
    if ($(element).hasClass("crit_selected")) {
        $(element).removeClass("crit_selected");
        $("#" + tabid).slideUp("fast");
        $(element).parents(".box_inner").parent().addClass("box_grey_large");
        $(element).parents(".box_inner").parent().removeClass("box_search_grey_large");
    } else {
        $(".box_inner_dyna:not(#" + $(element).attr("id") + "_tab)").css("display", "none");
        $(element).parents(".box_inner").parent().addClass("box_search_grey_large");
        $(".btn_crit").removeClass("crit_selected");
        $(element).addClass("crit_selected");
        $("#" + tabid).slideDown("fast");
        //$(this).parents(".box_inner").parent().removeClass("box_grey_large");
    }

    return false; // dÃ©sactive le href
}


var re1 = new RegExp("[ _'+&.:-]", "g");
var re2 = new RegExp("[Ã©Ã¨Ã«Ãª]", "g");
var re3 = new RegExp("[Ã¡Ã Ã¤Ã¢]", "g");
var re4 = new RegExp("[Ã¯]", "g");
var re5 = new RegExp("[Ã§]", "g");

function stripText(strText) {
    var retText = strText.toLowerCase();
    retText = retText.replace(re1, "");
    retText = retText.replace(re2, "e");
    retText = retText.replace(re3, "a");
    retText = retText.replace(re4, "i");
    retText = retText.replace(re5, "c");
    return retText;
}


function bestOfExtention() {
    return ($("#navbar .active").attr("id").toLowerCase().indexOf("bestof") > -1) ? "BestOf" : "";
}
var CFG_RESULT = {
    "BRANDS": {
        DivResult: '.filter_brand_result',
        DivWrapper: '.filtered_brand',
        Type: 'BrandID',
        fx: 'filterBrand'
    },
    "PRODUCTS": {
        DivResult: '.filter_product_result',
        DivWrapper: '.filtered_product',
        Type: 'ProductID',
        fx: 'filterProduct'
    },
    "AGENCIES": {
        DivResult: '.filter_agency_result',
        DivWrapper: '.filtered_agency',
        Type: 'AgencyID',
        fx: 'filterAgency'
    },
    "STUDIOS": {
        DivResult: '.filter_studio_result',
        DivWrapper: '.filtered_studio',
        Type: 'StudioID',
        fx: 'filterStudio'
    }
}
var CFG_WS = {
    "BRANDS": {
        method: 'GetBrandList',
        lang: true,
        result_cfg: CFG_RESULT.BRANDS
    },
    "PRODUCTS": {
        method: 'GetProductList',
        lang: true,
        result_cfg: CFG_RESULT.PRODUCTS
    },
    "AGENCIES": {
        method: 'GetAgencyList',
        lang: false,
        result_cfg: CFG_RESULT.AGENCIES
    },
    "STUDIOS": {
        method: 'GetStudioList',
        lang: false,
        result_cfg: CFG_RESULT.STUDIOS
    }
}
function handleResults(msg, cfg) {
    $(cfg.DivResult).children().remove();
    var found = 0;
    var items = msg.d.length;
    var rdb = [];
    for (var i = 0; i < items; i++) {
        if (msg.d[i][cfg.Type] == "-1") {
            $(cfg.DivWrapper + " .tomanyresult").show();
        } else {
            rdb.push("<li><a href=\"javascript:" + cfg.fx + bestOfExtention() + "('" + msg.d[i][cfg.Type] + "');\">" + msg.d[i].Description + "</a></li>");
        }
    }
    if (rdb.length > 0) {
        $(cfg.DivResult).append(rdb.join(""));
        $(cfg.DivWrapper + " .tomanyresult").hide();
        $(cfg.DivWrapper + " .noresult").hide();
        $(cfg.DivResult).show();
    } else {
        $(cfg.DivResult).hide();
        $(cfg.DivWrapper + " .tomanyresult").hide();
        $(cfg.DivWrapper + " .noresult").show();
    }
    $(cfg.DivWrapper).show();
}

function ajaxCall(txt, segment, callback) {
    callback = callback || function() { };

    var _data = "{'prefixText':'" + txt + "'" +
		((CFG_WS[segment].lang) ? (",'sLanguage':'" + curlang + "'") : ('')) +
		"}"
    $.ajax({
        type: "POST",
        url: "/webserv/SearchAutoComplete.asmx/" + CFG_WS[segment].method,
        data: _data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) { handleResults(msg, CFG_WS[segment].result_cfg); callback.call(); }
    });

}
function handleAjax(txt, id, callback) {
    clearTimeout(fieldCompare.timeout);
    if (txt.length > 1) {
        switch (id) {
            case "crit_brand_tab":
                /*BRAND/PROD*/
                ajaxCall(txt, "BRANDS")
                ajaxCall(txt, "PRODUCTS", callback)
                break;
            case "crit_agency_tab":
                /*AGENCIES*/
                ajaxCall(txt, "AGENCIES", callback)
                break;
            case "crit_studio_tab":
                /*STUDIOS*/
                ajaxCall(txt, "STUDIOS", callback)
                break;
            default: ;
        }

    } else {
        $(".filtered_product").hide();
        $(".filtered_brand").hide();
        $('.filter_brand_result').children().remove();
        $('.filter_product_result').children().remove();
        $(".filtered_agency").hide();
        $('.filter_agency_result').children().remove();
        $(".filtered_studio").hide();
        $('.filter_studio_result').children().remove();
    }
}

function stopClick(e) {
    if (window.event) {
        window.event.cancelBubble = true;
    } else {
        e.stopPropagation();
    }
}

function hoverTitle() {
    $("#upnContent #content_inner h2.hover_effect").hover(function() {
        var position = $(this).position();
        var heightH2 = $(this).height();
        var posTop = position.top + heightH2 + 17;
        $("#body_tooltip").css({ left: position.left, top: posTop }).show();
    }, function() {
        $("#body_tooltip").hide();
    });
}
