/**************** values checker *********************/
function CheckNumber(control, e)
{ 
    var keynum = '-1';
    // only allow numbers to be entered
    var checkOK = "0123456789";
    var checkStr = control.value;
    var allValid = true;
    var allNum = "";
    for (i = 0;  i < checkStr.length;  i++)
    {
        ch = checkStr.charAt(i);
        for (j = 0;  j < checkOK.length;  j++)
            if (ch == checkOK.charAt(j)) break;
            if (j == checkOK.length)
            {
                allValid = false;
                break;
            }
            if (ch != ",") allNum += ch;
    }
    if (!allValid)
    {
        control.value = control.value.substr(0,control.value.lenght-1);
        return (false);
    }

    var key;     
    if (window.event) key = window.event.keyCode;
    else if (e) key = e.which;
    if( key == '13')
    {
        control.blur();
    }
}

function disableEnterKey(e)
{
     var key;
     if (window.event) key = window.event.keyCode;
     else if (e) key = e.which;   
     return (key != 13);
}

function IDoUpdateValue(json , controlId , piloterControlId)
{
    con = document.getElementById(controlId);
    piloterControl = document.getElementById(piloterControlId);
    
    DoUpdateValue(json , con , piloterControl);
}

function DoUpdateValue(json , con , piloterControl)
{
    json = DecompressJSON(json);
    if(con.id == piloterControl.id)
    {
        if(CheckLimit(con))
        {
           if(con.value != json.ErgoIdentifier.Quantity)
           {
                json.ErgoIdentifier.Quantity = con.value - json.ErgoIdentifier.Quantity  ;
                ManageBasketAjax(json , null);    
           }
        }
    }
    else
    {
        if(CheckLimitVal(eval(con.value)  +  eval(json.ErgoIdentifier.Quantity)))
        {
            ManageBasketAjax(json , null);
        }  
    }
}

function CheckLimitVal(val)
{
   return CheckLimitWithValue(val);
}

function CheckLimit( control )
{ 
    return CheckLimitWithValue(control.value);
    //correction mantis 0018908  pour chrome 
    //return b ; 
}
function CheckLimitWithValue(control_value)
{
    // specify limits 
    return CheckLimits( control_value , 1 , Get_BasketLimitAddedArticles());
}

function CheckLimits( control_value , minLimit , maxLimit)
{
    // require a minimum  and a maximum 
    var chkVal = control_value;
    var prsVal = parseInt(control_value);
    if (chkVal == "" || prsVal*1 < minLimit*1 || prsVal*1 > maxLimit*1 )
    {
	    alertsay = "Veuillez choisir une quantit\351 comprise entre "+ minLimit +" et "+ maxLimit ;
        alert(alertsay);
        return false;
    }
    else
    {
        return true ;
    }
}
/******* JSON ajax manager *************/
String.prototype.replaceAll = function(stringToFind,stringToReplace){
    var temp = this;
    var index = temp.indexOf(stringToFind);
        while(index != -1){
            temp = temp.replace(stringToFind,stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    }

 function DecompressJSON(objJSON)
 {
 
  if(objJSON.toString().indexOf("|" , 0 ) != -1) // patch pour le json imbrique dans un appel javascript onclick
     {
        objJSON = objJSON.replaceAll("|","\""); // do decripting
        objJSON = objJSON.replaceAll("^",",");
        objJSON = eval('(' + objJSON + ')'); // eval json object 
     }   
     return objJSON;
 }
 function ManageBasketAjax(objJSON , oldHref)
 {
    if(objJSON=='')
    return true;
    objJSON = DecompressJSON(objJSON) ;
    
   
    var serverPageajaxManager = GetWWWDOtNetPathRoot() + '/Account/Basket/ErgoBasket/BasketAjaxRequestManager.aspx?w-4&';
    var strJSON = encodeURIComponent(JSON.stringify(objJSON.ErgoIdentifier));

   PreventClickWhenAjaxProcessing(true);
   
   $.ajax({ 
   type: "POST", 
   url: serverPageajaxManager,      
   data: 'strJSON='+ strJSON,
   dataType: "text",
   success: function(msg){
            // alert(msg);
             Respond(msg); moveWindow();  },
             
   error: function(XmlHttpRequest,textStatus,ErrorThrown){ HideAll() ; /*alert(ErrorThrown);*/ },
   timeout : 20000          
   });
   
    //alert(strJSON);
//        new Ajax.Request(serverPageajaxManager,
//           {
//            method: "post",
//            parameters: "strJSON=" + strJSON , // +"&"+ hrefParam[1],
//            onComplete: Respond
//           });
 }
 
function Respond(REQ)
 {
 
    REQ = eval ('('+REQ+')');
    //alert(REQ['allResult']);
    REQ = REQ['allResult'];
    nav = navigator.appName;
    var reg = '@@' ;
    if( nav == "Microsoft Internet Explorer"){	
        reg = new RegExp("(@@)");
    }
    
    var tableau = REQ.split(reg);
    
    
    var json_data_object = eval('(' + tableau[0] + ')');
    var panelResult = json_data_object.PanelId ;
    
    
    
    var reqText  = tableau[1];
    if( panelResult == null || panelResult == 'DefaultPanelID' )
    {
        ShowErgoBasket(reqText);
        HideWaitPanet();
    }
    else
    {
        var panelTarget = document.getElementById(panelResult);
        
        if(panelTarget != null)
        {
            //alert(json_data_object.UiUpdateMethod );
            if(json_data_object.UiUpdateMethod == 1 ) // append
            {
                var old_InnerHTML = panelTarget.innerHTML;
                if(json_data_object.UpdateMethodPlace == 0 ) // first 
                {
                    panelTarget.innerHTML =  reqText + old_InnerHTML ;
                }
                else
                {
                    panelTarget.innerHTML =  old_InnerHTML + reqText ;
                }
            }
            else
            {
                panelTarget.innerHTML = reqText;
            }
        }
        
        HideWaitPanet();
        HidePreventerWhenAjaxProcessing();
    }
    UpdateOthersPanel(tableau[2]);
    // cancel if panel none 
    if(panelResult =='none')
    {
        HideAll();
        return ; 
    }
    return false;
 }


function HideAll()
{
        HideWaitPanet();
        HidePreventerWhenAjaxProcessing();
        HideErgoPopin();
}

function UpdateOthersPanel(tableau)
{
    var json_options_object = eval("(" + tableau + ")");
    
    for ( x in json_options_object)
    {
       //alert(x);
       //alert(json_options_object[x]);
       if(document.getElementById(x))
       {
        var pTarget = document.getElementById(x).innerHTML = json_options_object[x];
        
       }
    }   
}
/******************************************* old ajax Manager  ********************/
// configuration 
var enableJsRedirectAjax = true; 
 
var nsv=document.layers;
var iev=document.all;
if(!iev)var mov=document.getElementById;
 
var fade=1;          // Pas de l'opacité en %
var fadetime=0;      // Interval en milliseconde de l'itération
var curfadeval=100;  // Valeur courante de l'opacité en %
var fadein=false;    // Sens du fade (boolean)
var debug = false;
//==========================================================================//
// TOOLS  : Définit l'opacité d'un objet en %  & Fade in et out de "divid"
//==========================================================================//
function SetOpacity(obj,val){
  if(!obj) return;
  if(!iev) 
  {
     obj.style.opacity = val/100; 
  }
	else obj.style.filter="alpha(opacity="+(val)+");";
  curfadeval=val;
} 
//==========================================================================//
function fadeinout(objectid){ 
  if(!nsv) var divid=document.getElementById(objectid);
  if(divid){
    if(fadein) curfadeval=curfadeval+fade;
    else curfadeval=curfadeval-fade;
    if(curfadeval>=100){
      curfadeval=100;
      fadein=false;
    }
    if(curfadeval<=0){
      curfadeval=0;
      fadein=true;
    }
    SetOpacity(divid,curfadeval);
  }
  setTimeout(fadeinout,fadetime);
}
//==========================================================================//






//==========================================================================//
/**
///<summary>
///Sets the innerHTML property of obj_id with the response from the passed url./
///</summary>
///<param name="url">The url to make the request to get the response data.</param>
///<param name="obj_id">The object or the id of the object to set the innerHTML for.</param>
*/
//==========================================================================//


jQuery.fn.center = function () { 
    //console.log("$(window).height() : "+$(window).height()+"| this.height() : "+$(this).height());
    $(this).css("position","absolute"); 
    $(this).css("top", ( $(window).height() - $(this).height() ) / 2+$(window).scrollTop() + "px"); 
    $(this).css("left", ( $(window).width() - $(this).width() ) / 2+$(window).scrollLeft() + "px"); 
    return this; 
} 

function HideErgoPopin()
{
    if(document.getElementById('add_selectionErgoPipeAjax') !=null)
    document.getElementById('add_selectionErgoPipeAjax').style.display = 'none';
    
    if(document.getElementById('MaskErgoPipeAjax')!= null)
    document.getElementById('MaskErgoPipeAjax').style.display ='none';
    
    if(document.getElementById('transLayout')!=null)
        $("#transLayout").hide();

    if(document.getElementById('hideLayout')!=null)
        $("#hideLayout").hide();        
        
}


function AddHeaderErgoBasket(contentValue , withclose)
{
    // valeur de personalisation de header
    var headerclose = "<div class='close floatr posrel mrg_r' style='z-index:999;cursor:pointer;'><img src='"+GetWWWDOtNetBaseUrl()+"/Img/decos/pipe/bt-fermer.png' onclick=\"HideErgoPopin()\" /> </div>";
    var header = "<div class='headerErgoBasket'><b class='tl'></b><div></div><b class='tr'></b></div>";
    if(withclose)
    header = header + headerclose;
    return header + contentValue ;
}

function AddFooterErgoBasket(contentValue)
{
    // valeur de personalisation de footer
    // for debugging ajax render use this div "<div id='errorPanel'>Bas de page : ------- @Fnac ------ </div>";
    var footer = "<div class='footerErgoBasket'><b class='bl'></b><div></div><b class='br'></b></div>";
     return  contentValue  + footer ;
}

var popin;
function ShowErgoBasket(contentValue , widthValue , withclose)
{
    var content = "<div style='margin-left:auto; margin-right:auto;' id='add_basketErgoPipeAjax'>"+contentValue+"</div>"; 
    content = AddHeaderErgoBasket(content , withclose);
    content = AddFooterErgoBasket(content);
    if(popin == null)
    {
        popin = document.createElement("DIV");    
        popin.id = "add_selectionErgoPipeAjax";    
        /*popin.className = "add_selection";    */
        document.body.appendChild(popin);     
        popin.style.position = "absolute";    
        popin.style.zIndex = "300"; 
        var popin_style_width = 390;
        if(widthValue != null)
        popin_style_width = widthValue;
        popin.style.width = popin_style_width + "px"; 
        popin.style.height = "auto";
        popin.style.border = "none";
        popin.style.left= (screen.width-popin_style_width)/2 +"px";    
        popin.style.top = 200+"px";
        
        /*popin.style.overflow  ='auto';*/
               
        popin.style.background = 'transparent';
    }   
    popin.innerHTML = content;  
    if(popin.style.display != "block")
    { popin.style.display = "block"; }
    if($("div#choiceMode").length > 0)
        updateCache(popin.offsetTop,popin.clientHeight);
    HideWaitPanet();
}

var preventer;
function moveWindow (){

    //var object = document.getElementById('add_selectionErgoPipeAjax');
    $('#add_selectionErgoPipeAjax').center(); 

}

function moveWaitWindow (){

    //var object = document.getElementById('add_selectionErgoPipeAjax');
    $('#WaitErgoPipeAjax').center(); 

}

function HidePreventerWhenAjaxProcessing()
{
    if(preventer == null)
    preventer = document.getElementById('MaskErgoPipeAjax') ;
    
    if(preventer != null)
    preventer.style.display = 'none';
}

var waiter = null ;
function HideWaitPanet()
{
    if(waiter == null )
    waiter = document.getElementById('WaitErgoPipeAjax') ;
    
    if(waiter != null)
    waiter.style.display = 'none';
}
var popinWait;
function ShowWaitPanet()
{
   
    if(popinWait == null)
    {
        popinWait = document.createElement("DIV");
        popinWait.id = "WaitErgoPipeAjax";
        document.body.appendChild(popinWait);
        popinWait.innerHTML = '<img src=\''+GetWWWDOtNetBaseUrl()+'/Img/decos/attente_anim.gif\' alt=\'loading....\' />' ; // can change this to make img or html content <font color=\'white\'>Waiting .....................</font>
        
        popinWait.style.position = "absolute";    
        popinWait.style.zIndex = "301"; 
        var popinWait_style_width = 61;
        popinWait.style.width = popinWait_style_width + "px"; 
        popinWait.style.height = "64px";
         
        popinWait.style.left = (screen.width-popinWait_style_width)/2 +"px";    
        popinWait.style.top = (screen.height-30)/2 +"px";    
    }
    //alert(popinWait.style.display);
    if(popinWait.style.display != "block") 
    { 
        popinWait.style.display = "block"; 
    }
     moveWaitWindow ();
}
var popinMask;
function PreventClickWhenAjaxProcessing(showWait)
{
    if( popinMask == null)
        {
            popinMask = document.createElement("DIV");
            popinMask.id = "MaskErgoPipeAjax";
            popinMask.style.background = 'black';
            SetOpacity(popinMask,50);
            popinMask.style.width = screen.width + "px"; 
            popinMask.style.height = document.body.clientHeight + "px";
            popinMask.style.zIndex= "299";
            popinMask.style.position = "absolute";
            popinMask.style.left= 0 +"px";    
            popinMask.style.top = 0+"px"; 
            if(window.addEventListener){ // Mozilla, Netscape, Firefox
            	
	            popinMask.addEventListener('click', HideWaitPanet, false);
            	
            } else { // IE
	             popinMask.attachEvent("onclick", HideWaitPanet);
            }
            document.body.appendChild(popinMask);
            var ie_style = ((/\bIS_IE7\b/).test(document.documentElement.className) || (/\bIS_IE\b/).test(document.documentElement.className)) ? true : false;
            var rH = (ie_style) ? document.body.clientHeight : document.body.offsetHeight;
            document.getElementById('MaskErgoPipeAjax').style.height = rH + "px";
        }
        if(popinMask.style.display != "block") 
        { 
            popinMask.style.display = "block";
        }
        
        //alert(showWait);
        if(showWait)
        ShowWaitPanet();
}


function updateCache(offst, pH) {
        document.getElementById('MaskErgoPipeAjax').style.height = offst + pH + "px";
}



  
  






