/*
  ***********************************************************************
  #  core.js
  #
  #  Common JS functions
  #
  #  $Revision:   1.2  $
  ***********************************************************************
 */
/** loading globally as the mouseovers are used throughout the site */
var ol_fgcolor = '#f0f0f0';
var ol_bgcolor = '#000000';
JSFX.Rollover("arrow_down", "/coe-images/home/arrow_down_on.jpg");
JSFX.Rollover("arrow_up", "/coe-images/home/arrow_up_on.jpg");
JSFX.Rollover("arrow", "/coe-images/home/arrow_on.gif");
JSFX.Rollover("arrow_left", "/coe-images/home/arrow_left_on.gif");
JSFX.Rollover("cart", "/coe-images/home/cart_on.gif");
// new use of cart for tup.com v6
JSFX.Rollover("icon_cart", "/coe-images/icon_cart_on.gif");

var indicatorImg = '<img src="/coe-images/indicator.gif" id="indicatorImg" />';
/**
 * doUpdate
 * required: fields (array of object) - an array containing an object describing the fields you want to check
 *              errorText: text to display on error ($('consultant_number').getAttribute('title'))
 *              id: dom id of the field to check
 *              labelId: dom id of the field label
 *              regEx: a regex to check; if null it will just check that a value has been entered.
 * required: postInfoIds (object) - an object describing the form and other actions
 *              statusMessage: message to display in a div with the id of 'status'
 *              statusMessageWidth: width of window.js Dialog
 *              statusMessageHeight: height of window.js Dialog
 * required: <div id="status" style="display:none;"></div> to display the status message (ID can be assigned via postInfoIds.statusId)
 * required: <div id="flash" style="display:none;"</div> to hold the error message (ID can be assigned via postInfoIds.flashId)
 * required: need to load the I18n phrase definitions
 *          <script type="text/javascript" language="JavaScript1.2" src="/coe-scripts/mytup_locale_def_CAN_FRC.js"></script>
*/
function doUpdate(fields,postInfoIds,doDialog,doSubmit,errorFields) {
    if (typeof(doSubmit) == 'undefined') { doSubmit = true; }
    if (typeof(doDialog) == 'undefined') { doDialog = false; }
    if (typeof(errorFields) == 'undefined') { errorFields = new Array(); }
    if (!postInfoIds.flashId) { postInfoIds.flashId = 'flash'; }
    if (!postInfoIds.statusId) { postInfoIds.statusId = 'status'; }
    if (!postInfoIds.formId) { postInfoIds.formId = 'formFields'; }
    if (!postInfoIds.submitId) { postInfoIds.submitId = 'submitBtn'; }
    if (!postInfoIds.statusMessage) { postInfoIds.statusMessage = 'Updating...'}
    if (!postInfoIds.flashBadAttention) { postInfoIds.flashBadAttention = 'Attention'}
    if (!postInfoIds.flashClose) { postInfoIds.flashClose = '[close]'}
    if (!postInfoIds.statusMessageWidth) { postInfoIds.statusMessageWidth = 200;}
    if (!postInfoIds.statusMessageHeight) { postInfoIds.statusMessageHeight = 75;}
    var errorMsg = '';
    var errorFldIdx = errorFields.length;
    if (fields) {
        for (i=0;i<fields.length;i++) {
            if (typeof(fields[i].regEx) == 'undefined') { fields[i].regEx = /./; }
            // since JS RegEx in IE is not standard we need to check minLen and maxLen to avoid regex conflicts
            if (typeof(fields[i].minLen) == 'undefined') { fields[i].minLen = 0; }
            if (typeof(fields[i].maxLen) == 'undefined') { fields[i].maxLen = 1000; }
            if (($F(fields[i].id) == '') ||
                ($F(fields[i].id).search(fields[i].regEx) == -1) ||
                ($F(fields[i].id).length < fields[i].minLen) ||
                ($F(fields[i].id).length > fields[i].maxLen)
                ) {
                errorFields[errorFields.length++] = {
                    id:fields[i].id,
                    //labelId:fields[i].labelId,
                    errorText:fields[i].errorText
                }
            } else {
                if (doSubmit) {
                    styles = $H({
                              background:'url(/coe-images/icon_yes.gif) right no-repeat'  // won't work in Safari due to a Webkit bug
                              });
                    if ($(fields[i].id).hasClassName('flashBadField')) {
                        $(fields[i].id).removeClassName('flashBadField').setStyle(styles);
                    } else {
                        $(fields[i].id).setStyle(styles);
                    }
                    //if ($(fields[i].labelId).hasClassName('flashBadLabel')) {
                    //    $(fields[i].labelId).removeClassName('flashBadLabel');
                    //}
                }
            }
        }
    }
    if (errorFields.length > 0) {
        $(postInfoIds.flashId).innerHTML = '';
        Effect.Appear(postInfoIds.flashId, {duration: 0.25});
        for (i=0;i<errorFields.length;i++) {
            new Effect.Highlight(errorFields[i].id,{startcolor:'#f0f0f0',endcolor:'#ffffff',duration:1.5});
            styles = $H({
                      background : 'url(/coe-images/icon_alert.gif) right no-repeat',
                      backgroundRepeat : 'no-repeat'  // to handle an IE bug
                      });
            $(errorFields[i].id).addClassName('flashBadField').setStyle(styles);
            //$(errorFields[i].labelId).addClassName('flashBadLabel');
            errorMsg += '<li>' + errorFields[i].errorText + '</li>';
            if (i == 0) {
                $(errorFields[i].id).focus();
            }
        }
        flashClose = '<div id="flashClose"><a href="javascript:void(0);" onclick="new Effect.Fade($(\'flash\'), {duration: 0.5});">'+ postInfoIds.flashClose +'</a></div>';
        $(postInfoIds.flashId).update('<div id="flashBad"><h5>'+ postInfoIds.flashBadAttention +':</h5><ul>' + errorMsg + '</ul>'+ flashClose + '</div>');
        return false;
    }
    if (errorFldIdx == 0) {
        if (doSubmit) {
            Effect.Fade(postInfoIds.flashId, {duration: 0.0});
            $(postInfoIds.flashId).innerHTML = '';
            Effect.Appear(postInfoIds.statusId, {duration: 0.25});
            msg = postInfoIds.statusMessage;
            $(postInfoIds.statusId).innerHTML = indicatorImg + msg;
            // issues in IE, leave it out for now.
            //var effect = new PopupEffect($(postInfoIds.submitId), {className: "overlay_alphacube"});
            //Dialog.info(msg,{windowParameters: {className: "alphacube",width:postInfoIds.statusMessageWidth, height:postInfoIds.statusMessageHeight,showEffect:effect.show.bind(effect),hideEffect:effect.hide.bind(effect)}, showProgress: true});
            if (doDialog) {
                Dialog.info(msg,{windowParameters: {className: "alphacube",width:postInfoIds.statusMessageWidth, height:postInfoIds.statusMessageHeight, closable:true}, showProgress: true});
            }
            $(postInfoIds.submitId).className = 'disabled';
            $(postInfoIds.submitId).disabled = true;
            $(postInfoIds.formId).submit();
        } else {
            return true;
        }
    } else {
        return false;
    }
}

/**
 * toggle
 * Used: throughout; common utility toggle switch
 * Handles most common toggle options
 */
function twxToggle(toggleInfo) {
    if (!toggleInfo.fieldId) { toggleInfo.fieldId = 'description'; }
    if (!toggleInfo.controlId) { toggleInfo.controlId = 'toggleCntl'; }
    //if (!toggleInfo.controlTextShow) { toggleInfo.controlTextShow = 'Hide'; }
    //if (!toggleInfo.controlTextHide) { toggleInfo.controlTextHide = 'Show'; }
    if (!Element.visible(toggleInfo.fieldId)) {
        new Effect.Appear(toggleInfo.fieldId, {duration: 0.25})
        if (toggleInfo.controlTextShow) {
            $(toggleInfo.controlId).update(toggleInfo.controlTextShow);
        }
        if (toggleInfo.fieldFlagId) {
            $(toggleInfo.fieldFlagId).value = '1';
        }
    } else {
        new Effect.Fade(toggleInfo.fieldId, {duration: 0.25})
        if (toggleInfo.controlTextHide) {
            $(toggleInfo.controlId).update(toggleInfo.controlTextHide);
        }
        if (toggleInfo.fieldFlagId) {
            $(toggleInfo.fieldFlagId).value = '0';
        }
        if (toggleInfo.formFieldId) {
            $(toggleInfo.formFieldId).value = '';
        }
    }
}

/**
 * LeftNav
 * Used: throughout; global left navigation menu controls
 *
 */
var LeftNav = {
    Items: new Array,
    childSuffix: '_child',
    add: function(navCode) { LeftNav.Items[LeftNav.Items.length++] = navCode; },
    show: function  (thisCode) {
        try {
            Effect.Appear(thisCode + LeftNav.childSuffix, {duration: 0.25});
            new Effect.Highlight(thisCode + LeftNav.childSuffix,{startcolor:'#efefef',endcolor:'#ffffff',duration:1.5});
            $(thisCode).setAttribute('class', 'globalLeftNavParent_on');
            for (i=0;i<LeftNav.Items.length;i++) {
                if (LeftNav.Items[i] != thisCode) {
                    Effect.Fade(LeftNav.Items[i] + LeftNav.childSuffix, {duration: 0.0});
                    if ($(LeftNav.Items[i]).className != 'globalLeftNavParent') {
                        $(LeftNav.Items[i]).setAttribute('class', 'globalLeftNavParent');
                    }
                }
            }
        } catch(err) {
            window.status = thisCode + ' is hidden; err: ' + err;
        }
    }
}

/* ***[ legacy calls tup_show_item ]********************************* */
/**
 * limitChars
 * Used: on gift certificate page for text field
 *
 */
function limitChars(numChars) {
    if(event.propertyName != "value") { return };
    var oTextArea = event.srcElement;
    var currTextLength = oTextArea.value.length;
    if(currTextLength > numChars) {
        // truncate TextArea
        oTextArea.value = oTextArea.value.substring(0, numChars);
    }
}
/**
 * change_val
 * to increment GC values
 */
function change_val(elId,num) {
    $(elId).value = $(elId).value - (-num);
    if (isNaN($(elId).value)==true) {
        $(elId).value = 10;
    }
    if ($(elId).value % 5 != 0) {
        alert(gcError.multiple);
        $(elId).value = Math.round(parseInt($(elId).value)/5)*5;
    }
    if ($(elId).value < 10){
        $(elId).value = 10;
    }
    if ($(elId).value > 250) {
        alert(gcError.maxLimit);
        $(elId).value = 250;
    }
}
/**
 * gcPutValue
 * Used: on gc page to copy gc values to forms
 *
 */
function gcPutValue(sValue) {
    sValue = sValue.split(':');
    $('fv_fname').value = sValue[0];
    $('fv_lname').value = sValue[1];
    $('fv_email').value = sValue[2];
    $('fv_message').value = sValue[4];
    $('fa_item_quantities').value = sValue[5];
    $('fv_gift_certificate_id').value = sValue[6];
    if(sValue[0]!=""){
        $('gcAdd').disable();
        $('gcDelete').enable();
        $('gcSave').enable();
    }else {
        $('gcAdd').enable();
        $('gcDelete').disable();
        $('gcSave').disable();
    }
    $('fv_fname').focus();
}

/**
 * ImagePreloader
 * Used: ccm$sso.p_login
 * Preloads all alphacube and validator images as they will appear to load slowly when called via AJAX calls
 */
function ImagePreloader(images,callback) {
    // store the callback
    this.callback = callback;

    // initialize internal state.
    this.nLoaded = 0;
    this.nProcessed = 0;
    this.aImages = new Array;

    // record the number of images.
    this.nImages = images.length;

    // for each image, call preload()
    for ( var i = 0; i < images.length; i++ )
        this.preload(images[i]);
}
ImagePreloader.prototype.preload = function(image) {
    // create new Image object and add to array
    var oImage = new Image;
    this.aImages.push(oImage);

    // set up event handlers for the Image object
    oImage.onload = ImagePreloader.prototype.onload;
    oImage.onerror = ImagePreloader.prototype.onerror;
    oImage.onabort = ImagePreloader.prototype.onabort;

    // assign pointer back to this.
    oImage.oImagePreloader = this;
    oImage.bLoaded = false;
    oImage.source = image;

    // assign the .src property of the Image object
    oImage.src = image;
}
ImagePreloader.prototype.onComplete = function() {
    this.nProcessed++;
    if ( this.nProcessed == this.nImages )
        this.callback(this.aImages);
}
ImagePreloader.prototype.onload = function() {
    this.bLoaded = true;
    this.oImagePreloader.nLoaded++;
    this.oImagePreloader.onComplete();
}
ImagePreloader.prototype.onerror = function() {
    this.bError = true;
    this.oImagePreloader.onComplete();
}
ImagePreloader.prototype.onabort = function() {
    this.bAbort = true;
    this.oImagePreloader.onComplete();
}
// load the alphacube and validator images
var aImg = ['/coe-scripts/windows_js/themes/alphacube/bottom-left-c.gif',
            '/coe-scripts/windows_js/themes/alphacube/bottom-middle.gif',
            '/coe-scripts/windows_js/themes/alphacube/bottom-right-c.gif',
            '/coe-scripts/windows_js/themes/alphacube/button-close-focus.gif',
            '/coe-scripts/windows_js/themes/alphacube/button-max-focus.gif',
            '/coe-scripts/windows_js/themes/alphacube/button-min-focus.gif',
            '/coe-scripts/windows_js/themes/alphacube/frame-left.gif',
            '/coe-scripts/windows_js/themes/alphacube/frame-right.gif',
            '/coe-scripts/windows_js/themes/alphacube/left-top.gif',
            '/coe-scripts/windows_js/themes/alphacube/right-top.gif',
            '/coe-scripts/windows_js/themes/alphacube/top-middle.gif',
            '/coe-images/indicator.gif'];
function confirmImages(aImages) {
    //window.status = 'Loaded '+ aImages.length +' images ('+ aImg.length +')';
}

 var MP = {
<!-- mp_trans_disable_start --> 
  Version: '1.0.22',
  Domains: {	'es':'espanol.tupperware.com',
				'fr':'francais.tupperware.ca'},	
  SrcLang: 'en',
<!-- mp_trans_disable_end -->
  UrlLang: 'mp_js_current_lang',
  SrcUrl: unescape('mp_js_orgin_url'),
<!-- mp_trans_disable_start --> 	
  init: function(){
    if (MP.UrlLang.indexOf('p_js_')==1) {
      MP.SrcUrl=window.top.document.location.href;
      MP.UrlLang=MP.SrcLang;
  }
},
getCookie: function(name){
  var start=document.cookie.indexOf(name+'=');
  if(start < 0) return null;
  start=start+name.length+1;
  var end=document.cookie.indexOf(';', start);
  if(end < 0) end=document.cookie.length;
  while (document.cookie.charAt(start)==' '){ start++; }
  return unescape(document.cookie.substring(start,end));
},
setCookie: function(name,value,path,domain){
  var cookie=name+'='+escape(value);
  if(path)cookie+='; path='+path;
  if(domain)cookie+='; domain='+domain;
  var now=new Date();
  now.setTime(now.getTime()+1000*60*60*24*365);
  cookie+='; expires='+now.toUTCString();
  document.cookie=cookie;
},
switchLanguage: function(lang){
  if(lang!=MP.SrcLang){
    var script=document.createElement('SCRIPT');
    script.src=location.protocol+'//'+MP.Domains[lang]+'/'+MP.SrcLang+lang+'/?1023749632;'+encodeURIComponent(MP.SrcUrl);
	document.body.appendChild(script);
  } else if(lang==MP.SrcLang && MP.UrlLang!=MP.SrcLang){
    var script=document.createElement('SCRIPT');
    script.src=location.protocol+'//'+MP.Domains[MP.UrlLang]+'/'+MP.SrcLang+MP.UrlLang+'/?1023749634;'+encodeURIComponent(location.href);
	document.body.appendChild(script);
  }
  return false;
},
switchToLang: function(url) {
  window.top.location.href=url; 
}
<!-- mp_trans_disable_end -->   
};
 
var TwxWindow = {
	   get : function (url,w,h,close,updateDiv) {
	        //new Ajax.Updater(this.alertId, '/pls/portal/!thp.ccm_page_views.p_ajx_alerts?x='+Math.floor(Math.random()*101), {
	        new Ajax.Updater(updateDiv, url, {	    	        
	        	method: 'get',	                 
	            onException: function(res,err) {window.status = 'Exception: '+err; },
	            onFailure:  function(res,err) {window.status = 'Failure: '+err;},
	            onSuccess: function(transport) {	                
	                var html= transport.responseText;
	                TwxWindow.openWindow(html,w,h,close);
	            }
	        });
	    },
	    openWindow : function (html,w,h,close) {	        
	        try {
	            win = Dialog.info(html,{windowParameters: {className: "alphacube",width:w,height:h, closable: close }});
	            // need to set zindex to prevent IE bug where iframes are displayed as windows.
	            win.setZIndex(999);
	        } catch(err) {
	            // for netscape and other older browsers; just in case...	            
	            var alrtWin=window.open('','name','height='+h+',width='+w);
	            alrtWin.document.write(html);	            
	            alrtWin.document.close();
	            alrtWin.moveTo(150,150);
	        }
	    },
	    show : function (url,w,h,close,updateDiv) {	    	
	        this.get(url,w,h,close,updateDiv);
	    }
	}




