
/*
 *It handle the window on resize event
 */
 window.onresize =  OnResizeHandler; 
/*
 *It handle the window on scroll event
 */
  window.onscroll =  OnScrollHandler; 
/* End of StringBuilder  Class */

/**
 * Stores object reference to those to be shown in a slide
 */
 var CurrentItemsToShow=null;
 /**
 * Stores object reference to those to be hidden in a slide
 */
 var CurrentItemsToHide=null;
 /**
 * Stores item index of current item  to be shown in a slide
 */
 var ToShowIndex=0;
 /**
 * Stores item index of current item  to be hidden in a slide
 */
 var ToHideIndex=0;
 /**
 * set time out speed
 */
 var CoreSlideSpeed=110;
 
 /**
 * Slides Next
 */
 function DoCoreSlideNext() {
    if (ToShowIndex<CurrentItemsToShow.length) {
       CurrentItemsToShow[ToShowIndex].style.display='';
       ToShowIndex++;
     }
    if (ToHideIndex<CurrentItemsToHide.length) {
            CurrentItemsToHide[ToHideIndex].style.display='none';
            ToHideIndex++;
    }
    if ((ToShowIndex<CurrentItemsToShow.length) ||(ToHideIndex<CurrentItemsToHide.length)) {
            setTimeout("DoCoreSlideNext()",CoreSlideSpeed);
     }
 
 }

 /**
 * Slides Prev
 */
 function DoCoreSlidePrev() {
   if (ToShowIndex>=0) {
       CurrentItemsToShow[ToShowIndex].style.display='';
       ToShowIndex--;
     }
    if (ToHideIndex>=0) {
            CurrentItemsToHide[ToHideIndex].style.display='none';
            ToHideIndex--;
    }
    if ((ToShowIndex>=0) ||(ToHideIndex>=0)) {
            setTimeout("DoCoreSlidePrev()",CoreSlideSpeed);
     }
 
 }
 
/**
 * OnResizeHandler
 */
function OnResizeHandler(){
    _QuickShop_Class.Hide(); //added on 3/23/07 to fix bug 194 on lancome
    if (!IS_MODELPOPUP_VISIBLE) return;
    _CoreModalPopUp.ResizeHandler();
    
}


/**
 * OnScrollHandler 
 */
function OnScrollHandler(){
    if (!IS_MODELPOPUP_VISIBLE) return;
    _CoreModalPopUp.ScrollHandler();
}

/**
 * This function is executed whenever a web service raises a run time error
 * If JAVASCRIPT_DEBUG is set to true an alert will be displayed with the actual message.
 * @param {object} result The JSON object returned by web service
 */



function onError(result) {
    DoDefault();
    window.status = "Web Service Error";
    if (result != null) {

       if (result.get_timedOut()) {
           alert('Your request timed out. Please try again');
       }
       else {
            var message = result.get_message();
            var stackTrace = result.get_stackTrace();
            var exceptionType = result.get_exceptionType();
            if (JAVASCRIPT_DEBUG) {
                alert(message + "..." + stackTrace + "...." + exceptionType );
            }
            else {
              alert("your request was not complete. Please try again" );
            }
        }
    }
}    

/**
 * This function is executed whenever a web service is timed out
 * If JAVASCRIPT_DEBUG is set to true an alert will be displayed.
 * @param {object} result The JSON object returned by web service
 */ 
function onTimeout(result) {
            DoDefault();
           // window.status = "web service call timed out";
            if (JAVASCRIPT_DEBUG) {
                        alert('web service call timed out. Please try again');
            }
}


/**
 * This function returns the customer ID that is assigned to a user
 * If Customer ID is missing and If JAVASCRIPT_DEBUG is set to true an alert
 * will be displayed with the actual message.
 */
function GetCurrentCustomerID() {
    if (CurrentCustomerID== null ||   typeof(CurrentCustomerID)=='undefined') {
        if (JAVASCRIPT_DEBUG)
                 alert('Customer ID is missing');
         return '';
    }
  return CurrentCustomerID;
}

/**
 * Some preliminary work for Mouse coordinates and browser type
 */
var tempX = 0;
var tempY = 0;

var IE = document.all?true:false;
if (!IE) document.captureEvents(Event.MOUSEMOVE)


/**
 * Attaching getMouseXY function onmousemove  event
 */
 /* TM : 06/18/2008 Commented as it creating flickering issue in IE with the drop down menus 
    as they were using onmouseover and onmouseout functions
document.onmousemove = getMouseXY;
*/
/**
 * Attaching HideQuick function onmouseup event
 */
//document.onmouseup = HideQuick;

/**
 * This function is used onmouseup event to hide the quick shop bubble
 */
function HideQuick(){
    _QuickShop_Class.Hide();
   
}


/**
 * This function stores in 2 global variable the mouse x coordinate and y Coordinate
 * @param {object} e Event object
 */
function getMouseXY(e) {
        if (IE) { // grab the x-y pos.s if browser is IE
            //if  (document.readyState != 'complete') return;
            if (!document) return;
            if(!document.body) return;
            tempX = parseInt(event.clientX) + parseInt(document.body.scrollLeft);
            tempY = parseInt(event.clientY) + parseInt(document.body.scrollTop);
        }
        else {  // grab the x-y pos.s if browser is NS
                tempX = e.pageX;
                tempY = e.pageY;
        }
        if (tempX < 0){tempX = 0;}
        if (tempY < 0){tempY = 0;}
        return true;
}

/**
 * Returns the temporary coordinate X of the Mouse
 */
function GetMouseCoordinateX() {
   return tempX;
}

/**
 * Returns the temporary coordinate Y of the Mouse
 */
function GetMouseCoordinateY() {
   return tempY;
}

/* End Mouse Coordinates */

/**
 * This function returns the Value attribute of a selected elemnt in a drop down.
 * @param {string} DropDownObjectID The ID of a drop down
 */
function GetSelectedValue(DropDownObjectID) {
        var x=document.getElementById(DropDownObjectID)
        //return (x.options[x.selectedIndex].text)
        return (x.options[x.selectedIndex].value)
}

/**
 * This function returns the text attribute of a selected element in a drop down.
 * @param {string} name DropDownObjectID The ID of a drop down
 */
function GetSelectedText(DropDownObjectID) {
        var x=document.getElementById(DropDownObjectID)
        return (x.options[x.selectedIndex].text)
}

/**
 * This function generataes the Option of a drop down based on JASON formatted Object Variants
 * Important Note: I am not using this function because I found a thread on the web
 * that this method raises IE error memory can not be referenced. Instead I am using a classic way
 * of building it via innerHTML of a DHTML element like div, span, etc....
 * I am currently using function "GenerateDropDownVariants"
 * @param {object} Variants JSON Serilized Object that Comes via web services Results
 * @param {string} ObjectToAppend The ID of a drop down to generate the options
 */
function BuildDropDownVariants(Variants,ObjectToAppend)
{
    if (Variants !=null )
    {
        for(i=0; i<Variants.length; i++)
        {
            var  option = new Option(Variants[i].Name + " - $ " + Variants[i].MainPrice ,Variants[i].SKU);
            ObjectToAppend.options[i] =option;
        }
    }
}

/**
 * This function builds the Drop Down. Be aware that I am using the javascrpt string builder class instead of
 * string concatinations.
 * @param {object} Variants JSON Serilized Object that Comes via web services Results
 * @param {string} DropDownID The ID of a drop down to generate the options
 */
function GenerateDropDownVariants(Variants,DropDownID,HasUniquePrices,ShowPriceOnDropDown,onchangeFuncCall)      
{
    var filter= _ProductBubble_Class.FilterVariantList;
    var sb = new StringBuilder();
    sb.append("");
    if (Variants != null ) {
        sb.append("<select id=\"");
        sb.append(DropDownID);
       // sb.append("\" class=\"Ablack11pxB\">");
      // sb.append("\" class=\"Ablack11pxB\" onchange=\"_ProductBubble_Class.SelectItem();\">");
        sb.append("\" class=\"Ablack11pxB\" onchange=\"" + onchangeFuncCall +"\">");
        
        for(i=0; i<Variants.length; i++)  {
          if (filter=='' || filter.indexOf(Variants[i].SKU)!=-1) {
            sb.append("<option value=\"");
            sb.append(Variants[i].SKU);
            sb.append("#");
            sb.append(Variants[i].MainPrice);
            sb.append("#");
            sb.append(Variants[i].StockWeb.toString());
            sb.append("\">");
            if (HasUniquePrices==true || ShowPriceOnDropDown==false) { //all vars same price
              sb.append(Variants[i].Name); 
           
            }
            else {//different variants different prices
              sb.append(Variants[i].Name   + " - $ " + Variants[i].MainPrice );
            }
            sb.append("</option>");
           }
        }
        sb.append("</select>")
    }
    //alert(sb.toString());
    return sb.toString();
}

/**
 * This function set selects a particular option of a drop down
 * @param {string} dropDownID The ID of a drop down
 * @param {string} valueToSelect Value to compare in order to select it
 */
function SetDropDownItemSelected(dropDownID,valueToSelect) {
    var selectedstr=valueToSelect;
    if (selectedstr.indexOf("#") != -1){
		selectedstr=selectedstr.slice(0,sku.indexOf("#"));
	}
    var options=document.getElementById(dropDownID)
    if (options!=null) {
        for (var i=0; i< options.length; i++) {
            var str = options[i].value;
			str = str.slice(0,str.indexOf("#"));
            if (str==selectedstr) { //valueToSelect
                options.selectedIndex=i;
                break;
            }
        }
    }
}

/**
 * This Function Determines the absolute coordinate X (Left) of any DHTML Object
 * @param {object} obj Obj is any DHTML Object for which we need to determine the absolute Coordinate X (Left)
 */
function findPosX(obj){
    var curleft = 0;

    if (obj.offsetParent){
        while(1){
            curleft += obj.offsetLeft;
            if (!obj.offsetParent)
            {
                break;
            }
            obj = obj.offsetParent;
        }
    }
    else if(obj.x){ curleft+=obj.x }

    return curleft;
}

/**
 * This Function Determines the absolute coordinate Y (Top) of any DHTML Object
 * @param {object} obj Obj is any DHTML Object for which we need to determine the absolute Coordinate Y (Top)
 */
function findPosY(obj){
    var curtop = 0;

    if (obj.offsetParent){
        while(1) {
            curtop += obj.offsetTop;
            if (!obj.offsetParent)
            {
                break;
            }
            obj = obj.offsetParent;
        }
    }
    else if(obj.y) { curtop+=obj.y }

    return curtop;
}

/**
 * This Function is used when on top of any DHTMl Object will be placed another DHTMl Object
 * It is used when I display the QuickShop Layer on top of the Product Image.
 * @param {object} RelativeObject This is any dhtml object, on our case it is a product Image
 * @param {object} ObjectToShow This is the Quick Shop DHTML Layer
 * @param {int} plusTop This will be an integer which will tell us the Top Position of the ObjectToShow
 * @param {int} plusLeft This will be an integer which will tell us the Left Position of the ObjectToShow
 */
function PositionLayerByRelativeObject(RelativeObject,ObjectToShow,plusTop,plusLeft) {
    var _xcoordinate=parseInt(findPosX(RelativeObject));
    var _ycoordinate=parseInt(findPosY(RelativeObject));
    
    if (!isNaN(plusLeft)){
        _xcoordinate=parseInt(_xcoordinate) + parseInt(plusLeft);
    }
    if (!isNaN(plusTop)){
        _ycoordinate=parseInt(_ycoordinate) + parseInt(plusTop);
    }

    ObjectToShow.style.visibility='visible';
    ObjectToShow.style.position='absolute';
    ObjectToShow.style.top=_ycoordinate + 'px';
    ObjectToShow.style.left=_xcoordinate + 'px';
}


/**
 * DoWait 
 */
function DoWait() {
        window.status = "";
       document.body.style.cursor='wait';
       TogglePleaseWait('visible',false)
}


/** 
 * DoDefault 
 */
function DoDefault() {
     document.body.style.cursor='default';
     TogglePleaseWait('hidden',false)
}

function DoDefaultWithoutEvent() {
     document.body.style.cursor='default';
     TogglePleaseWait('hidden',true)
}

function TogglePleaseWait(_Visibility, RaiseEvent) {
    var _pleaseWaitObject=$get(CORE_AJAX_PLEASEWAIT_DHTMLOBJECT_ID);
    if (_pleaseWaitObject!=null) {
        if (IS_MODELPOPUP_VISIBLE)
        {
            _CoreModalPopUp.Hide();
        }
        
        _pleaseWaitObject.style.visibility=_Visibility;
        if(CORE_AJAX_LOAD_PLEASEWAIT_ASMODAL) {
            _CoreModalPopUp._PopupControlID=CORE_AJAX_PLEASEWAIT_DHTMLOBJECT_ID;
            if (_Visibility=='visible') {
                _CoreModalPopUp.ShowModal();
            }
            else {
                if (RaiseEvent) {
                _CoreModalPopUp.HideModal();
            }
        else {
            _CoreModalPopUp.Hide();
        }
    }
}

    }
}

/**
 * IsAjaxLibraryLoaded is a boolean indicating wether the AJAX JavaScript
 * libraries have been loaded
 */
var IsAjaxLibraryLoaded=false;

/**
 * Fires when Atlas is loaded
 */
function AjaxOnload() {
       IsAjaxLibraryLoaded=true;
}

/** 
 * Determines if ATLAS has been loaded
 */
function IsAjaxLoaded() {
   return IsAjaxLibraryLoaded;
}


function pageLoad() {
  IsAjaxLibraryLoaded=true;
   MicrosoftFrance.MCS.Commerce.WS.AJAXProject.TopicWebService.set_timeout(WEB_SERVICE_TIMEOUT);
   MicrosoftFrance.MCS.Commerce.WS.AJAXProject.FavoritesWebService.set_timeout(WEB_SERVICE_TIMEOUT);
   MicrosoftFrance.MCS.Commerce.WS.AJAXProject.ProductWebService.set_timeout(WEB_SERVICE_TIMEOUT);
 //MicrosoftFrance.MCS.Commerce.WS.AJAXProject.CustomerWebService.set_timeout(WEB_SERVICE_TIMEOUT);
   MicrosoftFrance.MCS.Commerce.WS.AJAXProject.ShoppingCartWebService.set_timeout(WEB_SERVICE_TIMEOUT);
   MicrosoftFrance.MCS.Commerce.WS.AJAXProject.TopicWebService.set_timeout(WEB_SERVICE_TIMEOUT);
 //MicrosoftFrance.MCS.Commerce.WS.AJAXProject.CustomerWebService.set_path("http://" + location.host + "/ws/ajax/Customer.asmx");
}

function checkemail(value){
  var filter=/^.+@.+\..{2,3}$/
  return (filter.test(value))
}



/* ...... Functions below needs to be revisited ......  */

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_showHideLayers() { //v3.0
  var i,p,v,obj,args=MM_showHideLayers.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')?'visible':(v='hide')?'hidden':v;
		}
		obj.visibility=v;
	}
	//If there's a popup...
	//alert(args[3]);
	if(args[3] != null)
	{
		var layer = MM_findObj(args[0]);
		var popuptxt = MM_findObj(args[3]);
		var oBo = cBB (popuptxt);
		var oBp = cBB (layer);
		var left=0;
		var top=0;
		left=parseInt(oBo.l) + parseInt(popuptxt.offsetWidth) - 50;
		top=parseInt(oBo.t) - parseInt(layer.offsetHeight) + 15;
		if (isNaN(parseInt(left))) return false;
		if (isNaN(parseInt(top))) return false;
		layer.style.left = left + 'px';//40
    	layer.style.top = top +'px';
	}
}

function bx(x,y,w,h)
{
	this.l=x;
	this.r=x+w;
	this.t=y;
	this.b=y+h;
}

function cBB(o)
{
	var b=new bx(0,0,0,0);
	if(!o) return b;
	var x=0,y=0,p=o;
	while(p)
		{
		x+=p.offsetLeft;
		y+=p.offsetTop;
		p=p.offsetParent;
		}
	b.l=x;
	b.t=y;
	b.r=x+o.offsetWidth;
	b.b=y+o.offsetHeight;
	return b;
}
 
 
function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
}

function AJAX_GetTresHoldNumber() {
   var StockTresHold=5;
   if (typeof(OOS_THRESHOLD)!='undefined') { //placed this condition because the treshold was added after the site went live and in case the users have old version of js, the site will still run ok with no js errors.
               StockTresHold=parseInt(OOS_THRESHOLD);
   } 
   return StockTresHold;
}
