// jQuery blockUI plugin - http://malsup.com/jquery/block/jquery.blockUI.js?v2.17
(function(f){if(/1\.(0|1|2)\.(0|1|2)/.test(f.fn.jquery)||/^1.1/.test(f.fn.jquery)){alert("blockUI requires jQuery v1.2.3 or later!  You are using v"+f.fn.jquery);return}f.fn._fadeIn=f.fn.fadeIn;f.blockUI=function(m){c(window,m)};f.unblockUI=function(m){g(window,m)};f.growlUI=function(p,n,o){var m=f('<div class="growlUI"></div>');if(p){m.append("<h1>"+p+"</h1>")}if(n){m.append("<h2>"+n+"</h2>")}if(o==undefined){o=3000}f.blockUI({message:m,fadeIn:700,fadeOut:1000,centerY:false,timeout:o,showOverlay:false,css:f.blockUI.defaults.growlCSS})};f.fn.block=function(m){return this.unblock({fadeOut:0}).each(function(){if(f.css(this,"position")=="static"){this.style.position="relative"}if(f.browser.msie){this.style.zoom=1}c(this,m)})};f.fn.unblock=function(m){return this.each(function(){g(this,m)})};f.blockUI.version=2.18;f.blockUI.defaults={message:"<h1>Please wait...</h1>",css:{padding:0,margin:0,width:"30%",top:"40%",left:"35%",textAlign:"left",color:"#333",border:"none",backgroundColor:"transparent",cursor:"default"},overlayCSS:{backgroundColor:"#fff",opacity:"0.6"},growlCSS:{width:"350px",top:"10px",left:"",right:"10px",border:"none",padding:"5px",opacity:"0.6",cursor:null,color:"#fff",backgroundColor:"#000","-webkit-border-radius":"10px","-moz-border-radius":"10px"},iframeSrc:"javascript:false",forceIframe:false,baseZ:1000,centerX:true,centerY:true,allowBodyStretch:true,constrainTabKey:true,fadeIn:0,fadeOut:0,timeout:0,showOverlay:true,focusInput:true,applyPlatformOpacityRules:true,onUnblock:null,quirksmodeOffsetHack:4};var d=f.browser.msie&&/MSIE 6.0/.test(navigator.userAgent);var b=null;var e=[];function c(o,m){var y=(o==window);var p=m&&m.message!==undefined?m.message:undefined;m=f.extend({},f.blockUI.defaults,m||{});m.overlayCSS=f.extend({},f.blockUI.defaults.overlayCSS,m.overlayCSS||{});var x=f.extend({},f.blockUI.defaults.css,m.css||{});p=p===undefined?m.message:p;if(y&&b){g(window,{fadeOut:0})}if(p&&typeof p!="string"&&(p.parentNode||p.jquery)){var r=p.jquery?p[0]:p;var w={};f(o).data("blockUI.history",w);w.el=r;w.parent=r.parentNode;w.display=r.style.display;w.position=r.style.position;if(w.parent){w.parent.removeChild(r)}}var A=m.baseZ;var v=(f.browser.msie)?f('<iframe class="blockUI" style="z-index:'+(A++)+';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+m.iframeSrc+'"></iframe>'):f('<div class="blockUI" style="display:none"></div>');var u=f('<div class="blockUI blockOverlay" style="z-index:'+(A++)+';display:none;cursor:default;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');var q=y?f('<div class="blockUI blockMsg blockPage" style="z-index:'+A+';display:none;position:fixed"></div>'):f('<div class="blockUI blockMsg blockElement" style="z-index:'+A+';display:none;position:absolute"></div>');if(p){q.css(x)}if(!m.applyPlatformOpacityRules||!(f.browser.mozilla&&/Linux/.test(navigator.platform))){u.css(m.overlayCSS)}u.css("position",y?"fixed":"absolute");if(f.browser.msie){v.css("opacity","0.0")}f([v[0],u[0],q[0]]).appendTo(y?"body":o);var D=f.browser.msie&&(f.browser.version<8||!f.boxModel)&&(!f.boxModel||f("object,embed",y?null:o).length>0);if(d||(D&&q[0].style.setExpression)){if(y&&m.allowBodyStretch&&f.boxModel){f("html,body").css("height","100%")}if((d||!f.boxModel)&&!y){var E=j(o,"borderTopWidth"),s=j(o,"borderLeftWidth");var C=E?"(0 - "+E+")":0;var n=s?"(0 - "+s+")":0}f.each([v,u,q],function(t,H){var z=H[0].style;z.position="absolute";if(t<2){y?z.setExpression("height","Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.boxModel?0:"+m.quirksmodeOffsetHack+') + "px"'):z.setExpression("height",'this.parentNode.offsetHeight + "px"');y?z.setExpression("width",'jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"'):z.setExpression("width",'this.parentNode.offsetWidth + "px"');if(n){z.setExpression("left",n)}if(C){z.setExpression("top",C)}}else{if(m.centerY){if(y){z.setExpression("top",'(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"')}z.marginTop=0}else{if(!m.centerY&&y){var F=(m.css&&m.css.top)?parseInt(m.css.top):0;var G="((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "+F+') + "px"';z.setExpression("top",G)}}}})}if(p){q.append(p);if(p.jquery||p.nodeType){f(p).show()}}if(f.browser.msie&&m.showOverlay){v.show()}if(m.fadeIn){if(m.showOverlay){u._fadeIn(m.fadeIn)}if(p){q.fadeIn(m.fadeIn)}}else{if(m.showOverlay){u.show()}if(p){q.show()}}i(1,o,m);if(y){b=q[0];e=f(":input:enabled:visible",b);if(m.focusInput){setTimeout(l,20)}}else{a(q[0],m.centerX,m.centerY)}if(m.timeout){var B=setTimeout(function(){y?f.unblockUI(m):f(o).unblock(m)},m.timeout);f(o).data("blockUI.timeout",B)}}function g(p,q){var o=p==window;var n=f(p);var r=n.data("blockUI.history");var s=n.data("blockUI.timeout");if(s){clearTimeout(s);n.removeData("blockUI.timeout")}q=f.extend({},f.blockUI.defaults,q||{});i(0,p,q);var m=o?f("body").children().filter(".blockUI"):f(".blockUI",p);if(o){b=e=null}if(q.fadeOut){m.fadeOut(q.fadeOut);setTimeout(function(){h(m,r,q,p)},q.fadeOut)}else{h(m,r,q,p)}}function h(m,p,o,n){m.each(function(q,r){if(this.parentNode){this.parentNode.removeChild(this)}});if(p&&p.el){p.el.style.display=p.display;p.el.style.position=p.position;if(p.parent){p.parent.appendChild(p.el)}f(p.el).removeData("blockUI.history")}if(typeof o.onUnblock=="function"){o.onUnblock(n,o)}}function i(m,q,r){var p=q==window,o=f(q);if(!m&&(p&&!b||!p&&!o.data("blockUI.isBlocked"))){return}if(!p){o.data("blockUI.isBlocked",m)}if(m&&!r.showOverlay){return}var n="mousedown mouseup keydown keypress";m?f(document).bind(n,r,k):f(document).unbind(n,k)}function k(p){if(p.keyCode&&p.keyCode==9){if(b&&p.data.constrainTabKey){var o=e;var n=!p.shiftKey&&p.target==o[o.length-1];var m=p.shiftKey&&p.target==o[0];if(n||m){setTimeout(function(){l(m)},10);return false}}}if(f(p.target).parents("div.blockMsg").length>0){return true}return f(p.target).parents().children().filter("div.blockUI").length==0}function l(m){if(!e){return}var n=e[m===true?e.length-1:0];if(n){n.focus()}}function a(r,m,v){var u=r.parentNode,q=r.style;var n=((u.offsetWidth-r.offsetWidth)/2)-j(u,"borderLeftWidth");var o=((u.offsetHeight-r.offsetHeight)/2)-j(u,"borderTopWidth");if(m){q.left=n>0?(n+"px"):"0"}if(v){q.top=o>0?(o+"px"):"0"}}function j(m,n){return parseInt(f.css(m,n))||0}})(jQuery);
// Set up wrapper object
if(!TELUS){
  var TELUS = {};
};
TELUS.selectRegion = {
  LANGS : ['en','fr'],
  NOCONTENT : { residential : 'NT,NU,YT,INTL,USA' },
  MOBILITY_REGION_URL : 'www.telusmobility.com/en/common/js/setRegion.html',
  MYTELUS_REGION_URL : 'www.mytelus.com/order2/bundles/setRegion.vm',
  curr : {
    lang : null,
    region : null,
    customerType : null
  },
  init  : function(){
    var that = this;
    // reset modal CSS - to use CSS from stylesheet instead
    jQuery.blockUI.defaults.css = {};
    // smart defaults
    if(jQuery.cookie('lang')){
      jQuery("input:radio[value='"+jQuery.cookie('lang')+"']").attr('checked',true);
    };
    if(jQuery.cookie('CustomerType')){
      jQuery("input:radio[value='"+jQuery.cookie('CustomerType')+"']").attr('checked',true);
    };
    // set up click handlers
    // language options
    jQuery("#english-en,#french-en,#english-fr,#french-fr").bind('click',function(){
      jQuery(TELUS.selectRegion).trigger('changelanguage',[{lang:this.value}]);
      return true;
    });
    // personal/business
    jQuery('#personalUse-en,#personalUse-fr,#businessUse-en,#businessUse-fr').bind('click',function(){
      jQuery(TELUS.selectRegion).trigger('changecustomertype',[{type:this.value}]);
      return true;
    });
    // province links
    jQuery('.prov').bind('click',function(e){
      if(e.target.tagName.toLowerCase()=='a'){
        var el = e.target;
        // return if disabled
        if(el.parentNode.className.indexOf('disabled')>=0){
          return false;
        };
        jQuery(TELUS.selectRegion).trigger('changeregion',[{region:el.className.toUpperCase().split(' ')[0],target:el}]);
        return false;
      };
      return true;
    }).find('a').bind('focus',function(){
      if(this.parentNode.className.indexOf('disabled')>=0){
        this.blur();
        return false;
      };
      return true;
    });
    
    // assign listeners
    jQuery(this).bind('changelanguage',function(event, params){
      that.setLanguage(params);     
    });
    jQuery(this).bind('changecustomertype',function(event, params){
      that.setCustomerType(params);
    });
    jQuery(this).bind('changeregion',function(event, params){
      that.setRegion(params);
    });
    
    // select corresponding radio button in "opposite" language
    jQuery("input:radio").bind('click',function(){
      jQuery("#"+this.id.split('-')[0]+'-'+this.className.split(' ')[0])[0].checked = true;
      return true;
    }).filter(':checked').trigger('click');
  },
  setLanguage : function(options){
    var lang = options.lang || '';
    this.curr.lang = lang;
    // set language cookie   
    jQuery.cookie('lang',lang,{path:'/',expires:3650,domain:'telus.com'});
    // show/hide
    jQuery(TELUS.selectRegion.LANGS).each(function(){
       // hide the "opposite" language and show the selected one
       if(this!=lang){
        jQuery('body').addClass(lang).removeClass(this);
       };
    });    
    // enable/disable links
    this.doBusinessFrench();
  },
  setCustomerType : function(options){
    var custType = options.type || '';
    this.curr.customerType = custType;
    // set cookie
    jQuery.cookie('CustomerType',custType,{path:'/',expires:3650,domain:'telus.com'});
    // enable/disable links
    this.doBusinessFrench();
    return true;
  },
  setRegion : function(options){
    var region = options.region || '';
    var lang = this.curr.lang || 'en';
    this.curr.region = region;
    // set cookies
    // new 'prov' cookie (to match telusmobility.com)
    jQuery.cookie('prov',region,{path:'/',expires:3650,domain:'telus.com'});
    // portal region
    jQuery.cookie('telusPortalRegion',region,{path:'/',expires:3650,domain:'telus.com'});
    // telus.com legacy region cookie
    jQuery.cookie('TelusRegion',(region=='AB' || region=='BC') ? region.substr(0,1) : null,{path:'/',expires:3650,domain:'telus.com'});
    // set mobility cookie
    if(TELUS.selectRegion.NOCONTENT.residential.indexOf(region)==-1){
      // non-Safari browsers use iframe method
      if(!jQuery.browser.safari){
        try{
          // mobility
          jQuery('#frame-mobility-wrapper').remove();
          jQuery('body').append('<div id="frame-mobility-wrapper"></div>');
          jQuery('#frame-mobility-wrapper').html('<iframe style="height:1px;width:1px;display:none;" src="'+window.location.protocol+'//'+this.MOBILITY_REGION_URL+'?'+(new Date()).getTime()+'#'+region+'|'+lang+'" id="frame-mobility"></iframe>');
          // mytelus
          jQuery('#frame-mytelus-wrapper').remove();
          jQuery('body').append('<div id="frame-mytelus-wrapper"></div>');
          jQuery('#frame-mytelus-wrapper').html('<iframe style="height:1px;width:1px;display:none;" src="'+window.location.protocol+'//'+this.MYTELUS_REGION_URL+'?'+(new Date()).getTime()+'#'+region+'|'+lang+'" id="frame-mytelus"></iframe>');
        } catch(e) {};
      } else {
        // Safari uses window.open method
        var me = self;
        var regWin1 = window.open(window.location.protocol+'//'+this.MOBILITY_REGION_URL+'?'+(new Date()).getTime()+'#'+region+'|'+lang,'regWin1','location=0,status=0,scrollbars=0,width=1,height=1,menubar=0,resizable=0');
        var regWin2 = window.open(window.location.protocol+'//'+this.MYTELUS_REGION_URL+'?'+(new Date()).getTime()+'#'+region+'|'+lang,'regWin2','location=0,status=0,scrollbars=0,width=1,height=1,menubar=0,resizable=0');
        regWin1.moveTo(0,0);
        regWin2.moveTo(0,0);
        me.focus();
        jQuery(me).bind('unload',function(){
          regWin1.close();
          regWin2.close();
          return true;
        });
      };
    };
    if(this.curr.customerType=='residential' && this.curr.lang=='fr' && (this.curr.region=='BC'||this.curr.region=='AB')){
      jQuery.blockUI({
        message : '<div class="inner"><a class="close" onclick="jQuery.unblockUI();return false;" href="#">Fermez</a><h3>Aucun contenu disponible</h3><p>Actuellement, nous n’offrons pas la version française du contenu que vous avez demandé. Vous pouvez accéder au</p><ul style="margin-top:10px;margin-bottom:10px;"><li><a href="http://www.telusmobility.com/fr/'+this.curr.region+'/home/">telusmobilite.com en français</a><span style="padding: 7px 0 0 60px; display: block;">ou</span></li><li>au <a href="/">telus.com en anglais</a></li></ul><p>Merci de votre visite.</p></div>'
      });
      return false;
    };
    if(this.curr.customerType=='residential' && this.curr.lang=='en' && (TELUS.selectRegion.NOCONTENT.residential.indexOf(this.curr.region)>=0)){
      jQuery.blockUI({
        message : '<div class="inner"><a class="close" onclick="jQuery.unblockUI();return false;" href="#">Close</a><h3>Content not available</h3><p>We currently don\'t provide Personal products in the region you selected. You can either:</p><ul style="margin-top:10px;margin-bottom:10px;"><li><a href="/" onclick="jQuery.cookie(\'CustomerType\',\'business\',{path:\'/\',expires:3650,domain:\'telus.com\'});return true;">Access information for Business</a><span style="padding: 7px 0 0 60px; display: block;">or</span></li><li><a href="#" onclick="jQuery.unblockUI();return false;">Select a different region</a></li></ul><p>Thank you for visiting TELUS.</p></div>'
      });
      return false;
    };
    if(this.curr.customerType=='residential' && this.curr.lang=='fr' && (TELUS.selectRegion.NOCONTENT.residential.indexOf(this.curr.region)>=0)){
      jQuery.blockUI({
        message : '<div class="inner"><a class="close" onclick="jQuery.unblockUI();return false;" href="#">Fermez</a><h3>Aucun contenu disponible</h3><p>Nous n’avons actuellement aucune page concernant les renseignements demandés pour la province sélectionnée.</p><ul style="margin-top:10px;margin-bottom:10px;"><li><a href="/" onclick="jQuery.cookie(\'CustomerType\',\'business\',{path:\'/\',expires:3650,domain:\'telus.com\'});return true;">Consultez les pages sur nos solutions d’affaires</a><span style="padding: 7px 0 0 60px; display: block;">ou</span></li><li><a href="#" onclick="jQuery.unblockUI();return false;">Sélectionnez une autre région</a></li></ul><p>Merci de votre visite.</p></div>'
      });
      return false;
    };   
    if(this.curr.customerType=='business'){
      options.target.href = (this.curr.lang=='en') ? '/?'+(new Date()).getTime() : 'http://business.telus.com/fr_CA/QC/qcMlbMediumLargeBusinessHome.html';
      // change quebec link for business
      if(this.curr.region=='QC'){
        options.target.href = '/?'+(new Date()).getTime();
      };
    };
    // follow link - delayed to allow the hidden iframe to set the mobility cookie
    window.setTimeout(function(){location.href = (options.target.href);},200);
  },
  doBusinessFrench : function(){
    // enable/disable links
    if(this.curr.customerType=='business' && this.curr.lang=='fr'){
       jQuery("#fr ul.prov a[class!='QC']").parent().addClass('disabled');
     } else {
       jQuery("#fr ul.prov .disabled").removeClass('disabled');
     };
     // show/hide
     var custType = this.curr.customerType;
     var show = custType;
     var hide = (custType=='business') ? 'residential' : 'business';
     jQuery("#"+this.curr.lang).find('.column2 .'+show).show().end().find('.column2 .'+hide).hide();
  }
};
TELUS.selectRegion.init();