/* - Fonction : Redimension du texte
------------------------------------*/
var FS_OnePixel = 10; //1px in %
var FS_NormalPx = 10;
var FS_MoyenPx = 11;
var FS_GrandPx = 12;
var FS_MorePixel = 0;

$(document).ready(function() {
    // Font sizer
    $("#OutilsTexte a").each(function() {
        $(this).attr("href", "javascript:void(0);");
        $(this).click(function() {
            //Get size type
            var sizeType = $(this).attr("rel");
            switch (sizeType) {
                case "Grand":
                    newSize = FS_GrandPx;
                    break;
                case "Moyen":
                    newSize = FS_MoyenPx;
                    break;
                case "Normal":
                default:
                    newSize = FS_NormalPx;
            }
            var formattedSize = ((newSize + FS_MorePixel) * FS_OnePixel) + "%";
            $("#col_primaire").css("font-size", formattedSize);
            //Save in cookie
            $.cookie('font-size', newSize, { path: '/' });
            $.cookie('font-size-type', sizeType, { path: '/' });
            //Ajout de la classe active
            $("#OutilsTexte a").removeClass("On");
            $(this).addClass("On");
            AdjustColHeight();
        });
    });

    // Tooltip
    $(".tooltip").tooltip({
        delay: 0,
        showURL: false,
        bodyHandler: function() { return ttBodyHandler(this) }
    });
    $(".tooltip-delay").tooltip({
        delay: 750,
        showURL: false,
        bodyHandler: function() { return ttBodyHandler(this) }
    });

    // Pretty Checkbox
    ApplyPrettyCheckboxStyle('#ecrire_commentaire input[type=checkbox], #bloc_commentaire input[type=checkbox]');

    // Treeview
    $(".treeview-v1").treeview({ collapsed: true });
    $("#conteneur li.chapters span:first-child").each(function() {
        $(this)
			.prepend(
						$("<a>")
							.attr("href", "javascript:void(0);")
							.addClass("open-chapters")
							.click(function() { $(this).parents(".chapters").find(".chapters-list").slideToggle(); })
					);
    });
    // Sommaire bas de page dossier
    $("#btn_bottom_summary span").html(($("#bottom_summary").hasClass("open") ? "-" : "+"))
    $("#btn_bottom_summary").click(function() {
        $("#bottom_summary div.container")
			.slideToggle("fast", function() {
			    $(this).parent().toggleClass("open");
			    $("#btn_bottom_summary span").html(($(this).parent().hasClass("open") ? "-" : "+"));
			    AdjustColHeight();
			});
    });

    //Check la compatibilite du navigateur
    InitOldBrowser();

    // Balance Column Height
    AdjustColHeight();

    $(".tab_menu a").each(function() {
        $(this).click(function() {
            if (!$(this).parents("li").hasClass("actif")) {
                $(".tab_menu li, .tab_contenu").removeClass('actif');
                $(this).parents("li").addClass('actif');
                $("#" + $(this).attr("rel")).addClass('actif');
                AdjustColHeight();
            }
        });
    });

    $(".recherche_loading").click(function() {
        showLoading();
    });

    // Init popup video tout pv offre
    $(".toutpv-video").colorbox({ iframe: true, href: "/static/tout-pv-video.html", innerHeight:502, innerWidth:700 });

});
function AdjustColHeight() {
	if($("#col_tertiaire #dossier").length == 0) return;
	try {
		$("#col_primaire div.contenu:first").height("auto");
		var h_primaire = $("#col_primaire").height();
		var h_tertiaire = $("#col_tertiaire").height();
		if(h_tertiaire >= h_primaire) {
			$("#col_primaire div.contenu:first").height(h_tertiaire+50);
		}
	}catch(e){}
}
function ApplyPrettyCheckboxStyle(selector) {
    $(selector).prettyCheckboxes({
        checkboxWidth: 13, // The width of your custom checkbox
        checkboxHeight: 13 // The height of your custom checkbox
    });
}
// Tootip body handler
function ttBodyHandler(obj) {
    var data = obj.rel;
	var output = "<div class=\"pointeur\"></div>";
    if (data.charAt(0) == "#")
        output += eval(data.substr(1, data.length));
    else
        output += data;
		
	return output;
}

/* Fonction initialisation Taille du texte */
function initFontSize() {
    if ($("#OutilsTexte").length == 0) { return false; }
    //Set last size
    var cookieSize = $.cookie("font-size");
    var cookieSizeType = $.cookie("font-size-type");
    if (cookieSize) {
        var formattedSize = ((parseInt(cookieSize) + FS_MorePixel) * FS_OnePixel) + "%";
        //Ajout de la classe active
        $("#OutilsTexte a").removeClass("On");
        $("#OutilsTexte a." + cookieSizeType).addClass("On");
    }
    else {
        var formattedSize = ((FS_NormalPx + FS_MorePixel) * FS_OnePixel) + "%";
		$("#OutilsTexte a:first").addClass("On");
    }
    $("#col_primaire").css("font-size", formattedSize);
}


/* - Fonction : Equalcols height
   ------------------------------------*/
function equalHeight() {
    function _doIt() {
        var $z = $(arguments[0]);
        $z.height(Math.max.apply(Math, $z.map(function() { return $(this).height(); }).get()));
    }

    var $o = $(arguments[0]);
    var options = arguments[1] || {};
    var nbPerRow = options.nbPerRow;

    if (nbPerRow) {
        var max = Math.ceil($o.length / nbPerRow);
        for (var i = 0; i < max; ++i) {
            _doIt($($o.splice(0, nbPerRow)));
        }
    } else {
        _doIt($o);
    }
}

/* -- Fonctions gestion des popups DIV
-------------------------------------------*/
function ShowBoxAjax(id, anchor, focus) {
    HideAllBoxes();
    $("#" + id).show();

    if (focus == true || typeof (focus) == 'undefined')
        $("#" + id + " input:text:visible:first").focus();

    if (anchor && anchor != "")
        window.location = '#' + anchor;
}
function HideBoxAjax(id) {
    $("#" + id).hide();
}
function HideAllBoxes() {
    $("div.boite_ajax").hide();
    $("div.overlay").hide();
}

/*----------------------------------------------------------------------------*/
// Detection des vieux navigateurs
/*----------------------------------------------------------------------------*/
function OldBrowserDetect() {
    if (jQuery.browser.mozilla && jQuery.browser.version.substr(0, 3) < "1.9")//Firefox 2.0 et moins
        return true;
    else if (jQuery.browser.msie && jQuery.browser.version < "7.0")//IE 6.0 et moins
        return true;
    else if (jQuery.browser.safari && jQuery.browser.version <= "418.8")//Safari 2.0.4 et moins
        return true;
    else if (jQuery.browser.opera && jQuery.browser.version.substr(0, 1) < "9")//Safari 2.0.4 et moins
        return true;
    else
        return false;
}
function InitOldBrowser() {
    var cookieOldBrowser = $.cookie("OldBrowserError");
    if (OldBrowserDetect() && cookieOldBrowser == "") {
        var txtLang = "fr";
        var txtCloseBtn = "Fermer cette alerte";
        var txtTitle = "Votre navigateur n'est pas support&eacute;&nbsp;!";
        var txtDescription = "Pour une meilleure exp&eacute;rience web, prenez le temps de mettre votre navigateur &agrave; jour parmi un de&nbsp;ceux-ci.";
        var txtDownload = "T&eacute;l&eacute;charger";
        
        var box = "<div style='border: 1px solid #CA1600; background:#fffed7; text-align: center; clear: both; height: 90px; position: relative; margin:-10px 0 15px -10px;'>";
        box += "<div style='position: absolute; right: 3px; top: 3px; font-family: courier new; font-weight: bold;'><a href='#' onclick='javascript:CloseOldBrowser(this);'><img src='/images/navigateur/Bt_Fermer.gif' style='border: none;' alt='" + txtCloseBtn + "'/></a></div>";
        box += "<div style='width: 600px; margin: 0 auto; text-align: left; padding: 0 0 0 95px; overflow: hidden; color: black; background:#fffed7 url(/images/navigateur/Ico_Erreur.png) no-repeat 15px 18px; height:90px;'>";
        box += "<div style='width: 275px; float: left; font-family: Arial, sans-serif;'>";
        box += "<div style='font-size: 14px; font-weight: bold; margin-top: 12px;'>" + txtTitle + "</div>";
        box += "<div style='font-size: 12px; margin-top: 6px;'>" + txtDescription + "</div>";
        box += "</div>";
        box += "<div style='width: 75px; float: left;'><a href='http://www.mozilla.com/" + txtLang + "/' target='_blank'><img src='/images/navigateur/Img_Firefox.gif' style='border: none;' alt='" + txtDownload + " Firefox 3.5'/></a></div>";
        box += "<div style='width: 75px; float: left;'><a href='http://www.microsoft.com/downloads/details.aspx?FamilyID=341c2ad5-8c3d-4347-8c03-08cdecd8852b&DisplayLang=" + txtLang + "' target='_blank'><img src='/images/navigateur/Img_IE.gif' style='border: none;' alt='" + txtDownload + " Internet Explorer 8'/></a></div>";
        box += "<div style='width: 73px; float: left;'><a href='http://www.apple.com/" + (txtLang == 'fr' ? 'fr/' : '') + "safari/download/' target='_blank'><img src='/images/navigateur/Img_Safari.gif' style='border: none;' alt='" + txtDownload + " Safari 4'/></a></div>";
        box += "<div style='float: left;'><a href='http://www.google.com/chrome?hl=" + txtLang + "' target='_blank'><img src='/images/navigateur/Img_Chrome.gif' style='border: none;' alt='" + txtDownload + " Google Chrome'/></a></div>";
        box += "</div>";
        box += "</div>";
        jQuery("body").prepend(box);
    }
}
function CloseOldBrowser(obj) {
    obj.parentNode.parentNode.style.display = 'none';
    $.cookie('OldBrowserError', "true", { path: '/' });
    return false;
}


function submitenter(myfield,e,url)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	 
	if (keycode == 13)
	   {
	   return performSearch(myfield.id,url);
	   }
	else
	   return true;
}

function performSearch(id, url) {
    var query = getSearchQueryStringParameter(id, "keyword");
    if(query != '' && query != 'Trouvez un article paru depuis 1999' && query != 'Recherchez dans tout le site')
    {
        document.location.replace(url + '?' + query);
    }        
    return false;
}

function performAdvancedSearch(keywordsId, exactWordsId, excludeWordsId, themeId, subThemeId, pubDateId, authorId, url) {
    var keywords = getSearchQueryStringParameter(keywordsId, "keyword");
    var exactWords = getSearchQueryStringParameter(exactWordsId, "exact");
    var excludeWords = getSearchQueryStringParameter(excludeWordsId, "exclude");
    var theme = getSearchQueryStringParameter(themeId, "theme");
    var subTheme = getSearchQueryStringParameter(subThemeId, "sub");
    var pubDate = getSearchQueryStringParameter(pubDateId, "date");
    var author = getSearchQueryStringParameter(authorId, "author");

    var queryArray = new Array(keywords, exactWords, excludeWords, theme, subTheme, pubDate, author);
    var query = "";

    for (var i = 0; i < queryArray.length; i++) {
        if (queryArray[i] != "") {
            if (query == "") {
                query += "?";
            }
            else {
                query += "&";
            }
            query += queryArray[i];
        }
    }

    if (query != "") {
        document.location.replace(url + query);
    }

    return false;
}

function getSearchQueryStringParameter(id, paramName) {
    var queryStringParameter = $("#" + id).val();
    if (queryStringParameter != "") {
        queryStringParameter = paramName + "=" + queryStringParameter;
    }
    return queryStringParameter;
}

function loginsubmitenter(e,itemid){
if (document.getElementById) {
    var button = document.getElementById(itemid);
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;

    if (keycode == 13){
       button.click();
    }else
       return true;
    }
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_blockHideLayers() { //v6.0
  var i,p,v,obj,args=MM_blockHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'block':(v=='hide')?'none':v; }
    obj.display=v; }
}


var menu_status;

function showHide(itemid){
    //alert(itemid);
    //alert(document.getElementById(itemid).className);
    if(_pageLoadingIsCompleted)
    {
        if (document.getElementById) {
	        var switch_id = document.getElementById(itemid);
	        if(menu_status != 'show') 
	        {
		        // switch_id.className = 'show';
		        //alert('Show');
		        removeClass(switch_id, 'hide');
		        addClass(switch_id, 'show');
		        menu_status = 'show';
    			
	        }
	        else
	        {
		        // switch_id.className = 'hide';
		        //alert('Hide');
		        removeClass(switch_id, 'show');
		        addClass(switch_id, 'hide');
		        menu_status = 'hide';
	        }
        }
    }
}

function hasClass(el, className) {
    var re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
    return re.test(el.className);
}

function addClass(el, className) {
    if (hasClass(el, className)) { return; } // already present

    el.className = [el.className, className].join(' ');
}

function removeClass(el, className) {
    var re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', 'g');

    if (!hasClass(el, className)) { return; } // not present

    var c = el.className;
    el.className = c.replace(re, ' ');
    if ( hasClass(el, className) ) { // in case of multiple adjacent
	    removeClass(el, className);
    }
}

function writeOffer(path,id,width,height) {
    var so = new SWFObject(path, id, width, height, "6", "#ffffff");
    so.addParam("wmode", "transparent");
    so.write(id);
} 				

function fermerVolet(itemid) {
	if (document.getElementById) {
		var switch_id = document.getElementById(itemid);
		removeClass(switch_id, 'show');
		addClass(switch_id, 'hide');
	}
}

function ouvrirVolet(itemid){
	if (document.getElementById) {
		var switch_id = document.getElementById(itemid);
		removeClass(switch_id, 'hide');
		addClass(switch_id, 'show');
	}
}

function Suggerer(pURL, pDocumentID, pParams)
{
	jsURL= pURL + '?pDocumentID=' + pDocumentID + '&pParams=' + pParams;
	jsNom='suggerer';
	jsParam='toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,history=no,resizable=yes,width=405,height=525,left=1,top=1';
	window.open(jsURL, jsNom, jsParam)
}

function Hein()
{
    jsURL = "/Templates/EnvoyerTrouvailles.aspx";
	jsParam='toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,history=no,resizable=no,width=405,height=365,left=1,top=1';
	window.open(jsURL, "trouvailles", jsParam);
}

function Print(pURL, pDocumentID, pNodeTypeID)
{
	jsURL=pURL+'?pDocumentID='+pDocumentID+'&pNodeTypeID='+pNodeTypeID;
	jsNom='print';
	jsParam='toolbar=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=405,height=510,left=1,top=1';
	window.open(jsURL, jsNom, jsParam)
}

//DateSelection
function pv_daysinmonth(lnMonth,lnYear) {
    var dt1, cmn1, cmn2, dtt, lflag, dycnt, lmn
    lmn = lnMonth-1
    dt1 = new Date(lnYear,lmn,1)
    cmn1 = dt1.getMonth()
    dtt=dt1.getTime()+2332800000
    lflag = true
    dycnt=28
    while (lflag) {
       dtt = dtt + 86400000
       dt1.setTime(dtt)
       cmn2 = dt1.getMonth()
       if (cmn1!=cmn2) {
          lflag = false }
       else {dycnt = dycnt + 1}}
    if (dycnt > 31) {dycnt = 31}
    return dycnt
}

function pv_setdays(sobjname, datemode){
    var dobj = $get(sobjname + "D")
    var mobj = $get(sobjname + "M")
    var yobj = $get(sobjname + "Y")
    
    var hobj = $get(sobjname)
    var monthdays = pv_daysinmonth(mobj.options[mobj.selectedIndex].value,yobj.options[yobj.selectedIndex].value)
    var selectdays = dobj.length
    var curdy = dobj.options[dobj.selectedIndex].value
    if (curdy.length==1) {curdy = "0"+curdy}
    var curmn = mobj.options[mobj.selectedIndex].value
    if (curmn.length==1) {curmn = "0"+curmn}
    var curyr = yobj.options[yobj.selectedIndex].value
    if (selectdays > monthdays) {
       for (var dlp=selectdays; dlp > monthdays; dlp--) {
           dobj.options[dlp-1] = null }}
    else if (monthdays > selectdays) {
       for (var dlp=selectdays; dlp < monthdays; dlp++) {
           dobj.options[dlp] = new Option(dlp+1,dlp+1) }}       
    if (curdy > monthdays) {
       dobj.options[monthdays-1].selected = true
       curdy = monthdays }
    if (datemode==1) {
       var curdate = curmn+"/"+curdy+"/"+curyr }
    else if (datemode==2) {
       var curdate = curdy+"/"+curmn+"/"+curyr }
    else if (datemode==3) {
       var curdate = curyr+curmn+curdy }
    else if (datemode==4) {
       var cdate = new Date(curyr,curmn-1,curdy)
       var curdate = cdate.toGMTString() }
}

function ValidateLength(source, arguments) {
   arguments.IsValid = arguments.Value.length >= 6;
}

function ValidateInteger(textbox) {
    var entry = parseInt(textbox.value);
    if (isNaN(entry)) {
        entry = 0;
    }
    textbox.value = entry;
}

function ShoppingCartItemQuantityChange(buttonClientID, textBoxClientID, buttonUniqueID) {
    if (document.getElementById(textBoxClientID).value == "0") {
        __doPostBack(buttonUniqueID, '')
        return;
    }
    $("#" + buttonClientID).show();
}



