﻿ // Bell.ca bli077 - common.js

// Set the following variable to 'false' to set the title
// of the item identified by the id.  Set it to 'true' to
// set the title of the first <p> tag inside that item
// instead.


label = new Array()


label ['en'] = new Array();
label ['fr'] = new Array()


label['en']['main_reciver_label']='Primary receiver:';
label['fr']['main_reciver_label']='Récepteur principal&nbsp;:';
label['en']['additional_receiver_label']='Additional receivers:';
label['fr']['additional_receiver_label']='Récepteurs additionnels&nbsp;:';

label['en']['not_selected']='Not selected';
label['fr']['not_selected']='Non sélectionné';
//label['en']['standard']='Standard Satellite System';
//label['fr']['standard']='Standard fr';
label['en']['pvr']='PVR System';
label['fr']['pvr']='Système RVP';
label['en']['hd']='HD receiver';
label['fr']['hd']='Récepteur HD';
label['en']['hd_pvr_plus']='HD PVR Plus receiver';
label['fr']['hd_pvr_plus']='Récepteur vidéo personnel HD Plus';
label['en']['standard']='Standard receiver';
label['fr']['standard']='Récepteur de base';



label['en']['3']='$3.00';
label['fr']['3']='3.00$';
label['en']['5']='$5.00';
label['fr']['5']='5.00$';
label['en']['10']='$10.00';
label['fr']['10']='10.00$';
label['en']['15']='$15.00';
label['fr']['15']='15.00$';
label['en']['20']='$20.00';
label['fr']['20']='20.00$';

label['en']['monthly_total']='Monthly Total';
label['fr']['monthly_total']='Total par mois';

label['fr']['services']='Services';
label['en']['services']='Services';

label['fr']['options_and_features']='Options et équipement';
label['en']['options_and_features']='Features and equipement';


label['fr']['main_reciver_required']='Receiver principal non sélectionné';
label['en']['main_reciver_required']='Main receiver not selected';



var uglyParagraphPatch = true;


$(document).ready(function() {
	featureCheckbox.init();
	radioButton.init();
  
  Cufon.replace('#header h1', { fontFamily: 'BellSlim' });
  
	// External links in blank target
	$("a[@rel=external]").attr('target', '_blank');
	
	// Default values
	defaultValues.init();
});

defaultValues = {
	init : function() {
		var default_values = new Array();

	  $("input.default-value").focus(function() {
	    if (!default_values[this.id]) {
	      default_values[this.id] = this.value;
	    }
	    if (this.value == default_values[this.id]) {
	      this.value = '';
	    }
	    $(this).blur(function() {
	      if (this.value == '') {
	        this.value = default_values[this.id];
	      }
	    });
	  });
	}
}

settings = {
	initialized : false,
	
	init : function(val) {
		if (!this.initialized) {
			$.each(val, function(msg) {
				if (!settings[msg]) {
					settings[msg] = val[msg];
				};
			});
			
			this.initialized = true;
		} else {
			return false;
		};
	}
};

recommendation = {
	
	applyChanges : function(caller, recommendation1, recommendation2, lang, region)  {
		// Closing saving details.
		if ($("#toggleDetail").is(":visible")) {
			toggleDetail.toggle(lang,region);
		};

		if (!$("#"+recommendation1).is(":checked")) {
			if(!jQuery.browser.msie){$("#"+recommendation1).parent().next().find("div:eq(0) label").animate({opacity:"1.0"},1000);}
			$("#"+recommendation1).trigger('click');
		};
		if (!$("#"+recommendation2).is(":checked")) {
			if(!jQuery.browser.msie){$("#"+recommendation2).parent().next().find("div:eq(0) label").animate({opacity:"1.0"},1000);}
			$("#"+recommendation2).trigger('click');
		};
		$(caller).parent().parent().parent().css('display','none');
	}
}


homepage = {
	
	toggle : function(caller)  {
		if ($(".homeContent #wrapOverlay").css("display") == 'none') {
			$(".homeContent #wrapOverlay").slideDown()
			$(".homeContent #close").css("display", 'block')
		}else{
			$(".homeContent #wrapOverlay").slideUp()
			$(".homeContent #close").css("display", 'none')
		}	

		var targetOffset = $(caller).offset().top
		
	},
	
	toggleOffer : function(caller)  {
		$("#"+caller).slideDown();
		
		var targetOffset = $("#"+caller).offset().top
		$("html,body").animate({scrollTop:targetOffset},'slow')
	},
	
	closeOffer : function(caller)  {
		$("#"+caller).slideUp();
		
		
	}
}

receivers ={
	validate : function(lang, region, campaign, form){
		var params = {}; 
		inputs = $(form) .find(" input[@type='hidden'], input[@checked], input[@type='text'], input[@type='password'], input[@type='submit'], option[@selected], textarea") 
		.filter(":enabled");
		inputs.each(function() { 
			params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; }
			);

		$.ajax({
			type: "POST",
			url: "/"+lang+"/"+region+"/"+campaign+"/lines_of_business/checkrecivers.json",
			data: params,
			dataType: "json",
			timeout: 20000,
			success: function(msg) {
				output = "";
				
        /*
				if (msg.additional_hd_pvrs) {
					delete msg.additional_hd_pvrs;
					$("#additional_hd_pvrs").css('display','block')
					$("#additional_hd_pvrs").addClass('red');
				}else{
					$("#additional_hd_pvrs").removeClass('red');
				}
        */
        $("#features_errors").hide();
				$.each(msg, function(erreur) {
					output += msg[erreur]+'<br/>';
				});
        if(output.length > 0)
        {
          alert('output='+output);
          $("#features_errors").html(output);
          $("#features_errors").show();
				}
			}, 
			error: function(request, error, exeption){
			},
			complete: function(object, type){		
				
			}

		});		
	},
	save : function(lang, region, campaign, form){ // receivers
		var params = {}; 
		inputs = $(form) .find(" input[@type='hidden'], input[@checked], input[@type='text'], input[@type='password'], input[@type='submit'], option[@selected], textarea") 
		.filter(":enabled");
    $(".inputError").hide();
		inputs.each(function(){ params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; });

		$.ajax({
			type: "POST",
			url: "/"+lang+"/"+region+"/"+campaign+"/lines_of_business/checkrecivers.json",
			data: params,
			dataType: "json",
			timeout: 20000,
			success: function(msg) {
				output = "";
				var validation_passed= true;        
				if (msg.additional_hd_pvrs) {
					delete msg.additional_hd_pvrs;
					$("#additional_hd_pvrs").css('display','block')
					$("#additional_hd_pvrs").addClass('red');
					validation_passed=false;
				}else{
					$("#additional_hd_pvrs").removeClass('red');
				}
				
				$.each(msg, function(erreur){
					validation_passed=false;
					output += msg[erreur]+'<br/>';
				});
				
				$("#features_errors").html(output);
				if (validation_passed){          
					bundle.calculate(lang, region, campaign, form, 'additional_recivers');
					overlay.close();
				}
			}, 
			error: function(request, error, exeption){
			},
			complete: function(object, type){		
				
			}

		});		
	},
	
	reset : function(lang, region, campaign, form, default_selection){
		for (key in default_selection) {
			$('select[name*='+ key +'] option:contains('+ default_selection[key] +')').attr('selected','selected');
		};
	}
	
}

//need that to have access

featureCheckbox = {
		
	init : function(valeur, caller)  {
		var initialfeature = 0;
		var maxCount = $("#maxCount").html();
		
		$(".toggleDetail input[type=checkbox]:checked").each( function() {
		initialfeature += parseFloat($(this).attr("value"));
			}) 
		
		$(".toggleDetail #count").html("0");
	
		featureNumber = initialfeature;
		
		/*if ($("#OrderFeatureCallDisplay").attr('checked') != true){
			$("#OrderFeatureCallPrivacy").attr('disabled','disabled');
			//$("#OrderFeatureCallPrivacy").next().animate({opacity:"0.55"},1);  IE6 aime pas l opcaiter avec du texte bold
		}*/
		
		//if(featureNumber > maxCount) {
		//	$(".toggleDetail .error").css('display','block');
		//}else{		
		//	$(".toggleDetail .error").css('display','none');
		//}
	},
		
	disabler: function(valeur, caller, activeInputId) {
		var maxCount = parseFloat($("#maxCount").html());
		var featureNumber=0;	
			//counts all checked checboxes
			$("input[@type=checkbox]").each(function(){
				if ($(this).is(':checked')){
					featureNumber +=1;
				}
			});
		// if($("#"+caller).is(':checked')) {
		// 	featureNumber += parseFloat(valeur);
		// } else {
		// 	featureNumber -= parseFloat(valeur);
		// }
		
		// if ($("#"+caller).is(':checked')) {
		// 	$("#"+activeInputId).attr('disabled','')
		// } else {
		// 	$("#"+activeInputId).attr('disabled','disabled')
		// }
		
		featuresLeft = maxCount - featureNumber;
		if(featuresLeft>0) {
			$(".toggleDetail #count").html((featuresLeft).toString());
		} else {
			$(".toggleDetail #count").html("0");
		}
		
	},
	
	validate : function(lang, region, campaign, form){

		var params = {};
		inputs = $(form) .find(" input[@type='hidden'], input[@checked], input[@type='text'], input[@type='password'], input[@type='submit'], option[@selected], textarea") 
		.filter(":enabled");
		inputs.each(function() { 
			params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; }
			);

		$.ajax({
			type: "POST",
			url: "/"+lang+"/"+region+"/"+campaign+"/lines_of_business/checkfeatures.json",
			data: params,
			dataType: "json",
			timeout: 20000,
			success: function(msg) {
				//init the validation
				output = "<span class=\"error_ico\">&nbsp;</span>";
				if (msg.feature_visual_call_waiting) {
					delete msg.feature_visual_call_waiting;
					$("#features_errors").css('display','block')
					$("#feature_visual_call_waiting_count").addClass('red');
				}else{
					$("#feature_visual_call_waiting_count").removeClass('red');
				}
				
				if (msg.features_count) {
				$("#features_errors").css('display','block')
					delete msg.features_count;
				}
				
				if (msg.feature_call_privacy) {
					$("#features_errors").css('display','block')
					$("#feature_call_privacy_requires").addClass('red');
				}else{
					$("#feature_call_privacy_requires").removeClass('red');
          
				}
        var error_count = 0;
				$.each(msg, function(erreur) {
					output += msg[erreur]+'<br/>';
          error_count++;
				});
        
        if(error_count == 0)
          $("#features_errors").hide();
        else
          $("#features_errors").html(output);
			}, 
			error: function(request, error, exeption){
			
			},
			complete: function(object, type){	

			}

		});	
		
	},
	
	save : function(lang, region, campaign, form)  { // features cb
		var params = {};
		inputs = $(form) .find(" input[@type='hidden'], input[@checked], input[@type='text'], input[@type='password'], input[@type='submit'], option[@selected], textarea") 
		.filter(":enabled");
		inputs.each(function() { 
			params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; }
			);

		$.ajax({
			type: "POST",
			url: "/"+lang+"/"+region+"/"+campaign+"/lines_of_business/checkfeatures.json",
			data: params,
			dataType: "json",
			timeout: 20000,
			success: function(msg) {
				//init the validation
				output = "<span class=\"error_ico\">&nbsp;</span>";
				var validation_passed= true;
				if (msg.feature_visual_call_waiting) {
					delete msg.feature_visual_call_waiting;
					$("#features_errors").css('display','block')
					$("#feature_visual_call_waiting_count").addClass('red');
					validation_passed= false;
				}else{
					$("#feature_visual_call_waiting_count").removeClass('red');
				}
				
				if (msg.features_count) {
					$("#features_errors").css('display','block')
					validation_passed= false;
				}
				
				if (msg.feature_call_privacy) {
					$("#features_errors").css('display','block')
					$("#feature_call_privacy_requires").addClass('red');
					validation_passed= false;
				}else{
					$("#feature_call_privacy_requires").removeClass('red');
				}
				$.each(msg, function(erreur) {
					output += msg[erreur]+'<br/>';
					validation_passed= false;
				});
				
				$("#features_errors").html(output);
				//have to close and update
				if (validation_passed){
					bundle.calculate(lang, region, campaign, form,'featureCount');
          url_call = "/"+ lang +"/"+ region + "/" + campaign +"/lines_of_business/checkfeatures?"+ str.random();
          $("#features_homephone_listing").load(url_call ,null, function() {

					});
          
					overlay.close();
				}
			}, 
			error: function(request, error, exeption){
			
			},
			complete: function(object, type){	
		  }

		});
	},
	reset : function(lang, region, campaign, form, default_selection){
		// Deseclect all checkboxes
		$("input[@type=checkbox]").each(function(){
			$(this).attr('checked','');
		});

		// Loop in the default selections and select them
		for (var i=0; i < default_selection.length; i++) {
			$('input[name*='+default_selection[i]+']').attr('checked','checked');
		};
		$("#count").html("");
		$("#features_errors").css('display','none');
	}
	
}

toggleDetail = {
	
	toggle: function(lang,region) {
		// Reset timer
		timer.init();
		
		if($("#toggleDetail").css('display') != "none") {
			offset = $('#calculator').offset();
			$("#toggleDetail").css('top',offset.top - 37);
			$("#toggleDetail").animate({left:"408px"},500,function(){
				$("#toggleDetail").hide();
			})
			$("#toggleDetail .terms").css('overflow','hidden');
			
			if($.browser.msie && $.browser.version == 6){
				$('select').show();
			}
		}else{
			if($.browser.msie && $.browser.version == 6){
				$('select').hide();
			}
			
			// Load content
			toggleDetail.load(lang,region);
	
			omniture.send(lang,region,"savings-details");
		}
		
	},
	
	load: function(lang,region) {
		var url = "/"+lang+"/"+region+"/lines_of_business/";
		$("#toggleDetail").load(url + "savings-details.ajax?" + str.random(),null, function() {
			// Display content
			if (!$("#toggleDetail").is(":visible")) {
				$("#toggleDetail").show();
				$('#toggleDetail').css({'top':$('#calculator').offset().top - 37});
				$("#toggleDetail").animate({left:"0px"},500);
			}
			
			$("#toggleDetail .terms").css('overflow-y','scroll');
			
		});
	},
	
	close: function() {
		if($("#toggleDetail").css("left") == "0px") {
			$("#toggleDetail").animate({left:"408px"},500)
			$("#toggleDetail .terms").css('overflow','hidden')
		}
	}
}

radioButton = {
	init : function() {
		// To display the field as disabled when they are unchecked on load
		$('ul.combination > li').each(function(){
			if($(this).find('input[type=checkbox]:eq(0)').not(':checked').size() > 0){
        // ZZZ : remove init call that cause recalculate on loading
				radioButton.toggleRadio($(this).find('input[type=checkbox]:eq(0)').not(':checked'));
			}
		});
	},
	toggleRadio : function(caller) {
		// Reset timer
		timer.init();
		
		// Exception is it's a long distance click
		if($(caller).attr('id') == 'OrderServiceLongDist'){
			if($(caller).is(":checked")){
				// Slide the radios
				$(caller).nextAll('ul.hide:eq(0)').css('visibility','visible').slideDown().find('input:eq(0)').attr('checked','checked');
				
				// Check the service
				// If it's not checked, check it
				if($(caller).parent().parent().parent().find('input[type=checkbox]:first').is(':not(:checked)')){
					$(caller).parent().parent().parent().find('input[type=checkbox]:first').trigger('click');
					
					// Then select keep current service
					$(caller).parent().parent().parent().find('p.keep input[type=radio]:first').attr('checked','checked');
				}
			}else{
				$(caller).nextAll('ul.hide:eq(0)').slideUp();
			}
		}else{
			if ($(caller).is(":checked")) {
				$(caller).parent().find('label:gt(0)').css('color','#595959'); /* Find all the labels and fake the enabled effect */
				$(caller).parent().find('input:gt(1)').attr("disabled", ""); /* Enable all the inputs */
				$(caller).parent().find('input[type=radio]:eq(1)').attr({"checked":"checked"});
			} else {
				$(caller).parent().find('label:gt(0)').css('color','#a7a7a7'); /* Find all the labels and fake the disabled effect */
				$(caller).parent().find('input:gt(1)').attr({"disabled": "disabled", "checked":""}); /* Disable all the inputs */
			};
			
			// If the caller is home phone, we need to leave long distance activated.
			if($(caller).attr('id') == 'OrderServiceHomePhone'){
				$(caller).parent().find('ul.other label').css('color','#595959');
				$(caller).parent().find('ul.other input').attr("disabled", "");
				
				// If the long distance checkbox is checked, show the list
				if($(caller).parent().find('ul.other input:checkbox:eq(0):checked').attr('id')){
					$(caller).parent().find('ul.other ul.hide:eq(0)').css('visibility','visible').slideDown();
				}
			}
		}
		updateCalculator();
	}
}

function unfoldList(theitem) {
  var item = document.getElementById(theitem);
  var foldWithInput = item.className.indexOf("foldWithInput") != -1 ? " foldWithInput" : "";
  var foldStr;
  if (item.className.indexOf('fold') == 0) {
		foldStr = 'unfold';
  } else {
		foldStr = 'fold';
  }
  item.className = foldStr + foldWithInput;

  var label = getToggleListLabel(theitem, item.className);
	if(label != undefined) {
		if(uglyParagraphPatch) {
			var paras = item.getElementsByTagName("p");
			if(paras.length>0) {
				paras[0].title=label;
			}
		} else {
			item.title=label;
		}
	}
}

var toggleLists = {};
function setToggleListLabel(list, clazz, label) {
	var item = toggleLists[list];
	if(item == undefined) {
		toggleLists[list] = {};
	}
	toggleLists[list][clazz] = label;
}

function getToggleListLabel(list, clazz) {
	var label = undefined;
	if(toggleLists[list] != undefined) {
		label = toggleLists[list][clazz];
	}
	return label;
}

function initToggleListLabels(clazz) {
	for(var listId in toggleLists) {
		var item = document.getElementById(listId);
		var label = getToggleListLabel(listId, item.className);
		if(label != undefined) {
			if(uglyParagraphPatch) {
				var paras = item.getElementsByTagName("p");
				if(paras.length>0) {
					paras[0].title=label;
				}
			} else {
				item.title=label;
			}
		}
		if(clazz != undefined) {
			item.className=clazz;
		}
	}
}

function toggleOneItem(theitem) {
  if((document.getElementById(theitem).style.display == 'block') || (document.getElementById(theitem).style.display == -1))
    document.getElementById(theitem).style.display = 'none';
  else
    document.getElementById(theitem).style.display = 'block';
}

function toggleTwoItem(theitem1, theitem2) {
  if((document.getElementById(theitem1).style.display == 'none') || (document.getElementById(theitem1).style.display == -1))
  {
    document.getElementById(theitem1).style.display = 'block';
    document.getElementById(theitem2).style.display = 'none';    
  }
}

function toggleClass(theitem) {
  // getter
  // ==================================
  el = document.getElementById(theitem);
  classes = el.className;
  
  //setter
  // ==================================
  if(classes.match(/close.*?/)) { //check if the item is close
  	var state = 'open';
  } else {
    var state = 'close';
  }
  
  // set state classname
  newClass = state;

  // check for any space which mean the element have more than one class
  if(classes.match(/ .*?/)) {
    classes = classes.split(" ");      
    for(i = 1; i < classes.length; i++) {
      newClass += " " + classes[i];
    }    
  }
  
  // apply new class to element
  el.className = newClass;
}

function changeClassName(theitem, NewclassName) {
  if((document.getElementById(theitem).className != NewclassName)) {
    document.getElementById(theitem).className = NewclassName;
  }
}

function enableSubmit(checkBoxID, buttonID) {
	if(document.getElementById(checkBoxID).checked == true) {
		document.getElementById(buttonID).disabled = false;
		changeClassName(buttonID,'alignRight enabled');
	}
	else {
		document.getElementById(buttonID).disabled = true;	
		changeClassName(buttonID,'alignRight disabled');	
	}	
}

var checkflag = "false";
function check(field) {
  if (checkflag == "false") {
    for (i = 0; i < field.length; i++) {
      field[i].checked = true;
    }
    checkflag = "true";
    return "Uncheck All";
    } else {
      for (i = 0; i < field.length; i++) {
      field[i].checked = false;
    }
    checkflag = "false";
    return "Check All"; }
}

var speed = 5;
var target = -3;

function yMove(objectID) {  
  var objMove = document.getElementById(objectID)
  /*console.log(objectID,objMove);*/
  if (parseInt(objMove.style.top) < target) {
    objMove.style.top=parseInt(objMove.style.top)+speed+"px"
    yMoveVar = setTimeout("yMove('"+objectID+"')",20)
  } else {
    clearTimeout(yMoveVar);
  }
}       

var yspeed = -5;
var ytarget = 100;

function yMoveMore(objectID) {  
  var objMove = document.getElementById(objectID);     
                
  if (parseInt(objMove.style.top) > ytarget) {
    objMove.style.top=parseInt(objMove.style.top)+yspeed+"px"
    yMoveVar = setTimeout("yMoveMore('"+objectID+"')",20)     
 
  } else {
    clearTimeout(yMoveVar);
  }
}

var targetHide = -108;

function yHide(objectID) {  
  var objMove = document.getElementById(objectID)

  if (parseInt(objMove.style.top) > targetHide) {
    objMove.style.top=parseInt(objMove.style.top)-speed+"px"
    var yHideVar = setTimeout("yHide('"+objectID+"')",20)
  } else {
    clearTimeout(yHideVar);
  }
}


function setFlashWidth(divid, newW){
	document.getElementById(divid).style.width = newW+"px";
}
function setFlashHeight(divid, newH){
	document.getElementById(divid).style.height = newH+"px";
}
function setFlashSize(divid, newW, newH){
	setFlashWidth(divid, newW);
	setFlashHeight(divid, newH);
}
function canResizeFlash(){
	var ua = navigator.userAgent.toLowerCase();
	var opera = ua.indexOf("opera");
	if( document.getElementById ){
		if(opera == -1) return true;
		else if(parseInt(ua.substr(opera+6, 1)) >= 7) return true;
	}
	return false;
}



function flashToUrl(url, method) {
  //method is set to null by default
  var method;
   
  if (!method) {
    location.href = url;
  } else if(method == '_blank') { // if flash movie set a variable _blank we open in a new window
    window.open(url,'','toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes'+',width='+800+',height='+600+',left='+25+',top='+25);
  }
  sendModifiedOmniturePageName('flashlink');
}

function gotoSite(thisUrl, thisWidth,thisHeight,thisTop,thisLeft) {

     var url = '/shopping/popups/personal/leaving.jsp?url=' + thisUrl;
     optionString = ('width=' + thisWidth + ',height=' + thisHeight + ',top=' + thisTop + ',left=' + thisLeft + ',status=no,menubar=no,resizable=yes,scrollbars=yes');
     mainWin = window.open(url,'goExternal',optionString);

 }


// Internet support landing support
function openSupportTopic(el) {
  // user selection element id
  selectedElement = el.parentNode;
  
  // array list of LI - base DOM path is AHREF
  var topics;
  topics = el.parentNode.parentNode.getElementsByTagName('li');

  // remove any className active
  for(i = 0; i < topics.length; i++) {
    topics[i].className = "";
  }
  
  // set className "active" to selectedElement
  selectedElement.className = "active";
  
  // --------------------------------------------
  // Open related content
  // --------------------------------------------
  
  temp = selectedElement.id + "_details";
  if(document.getElementById(temp)) {
    contentDetails = document.getElementById(temp);  
      
    // array list of LI - base DOM path is LI
    var topicDetails;
    topicDetails = contentDetails.parentNode.getElementsByTagName('li');

    // remove any className "active"
    for(j = 0; j < topicDetails.length; j++) {
      topicDetails[j].className = "";
    }

    // set className "active" to contentDetails
    contentDetails.className = "active";    
  }


}

function gotoUrl(url) {
	location.href = url; 
}




overlay = {
	open : function(pageToOpen,caller, lang, region, pageName){
		// Stop timer 
		timer.stop();
		
		overlay.displayLoader();
		
		overlay.buildOverlay();
		
		var currentTime = new Date()
		
		if (pageName=="features_phone" || pageName=="features_television"){
			pageToOpen=pageToOpen + "/"+pageName +"/";
		}
		
		$('div.overlayContainer').load(pageToOpen + "?=" + currentTime.getMilliseconds(),'',function(){
			scrollPos = getScroll();

			windowtop = ($(window).height()/2) + scrollPos['scrollTop'] - ($('div.overlayContainer').height()/2);
			if (windowtop < 0) {
				windowtop = 10;
			};

			$('div.overlayContainer').css({
				'top': windowtop,
				'left': ($(window).width()/2) + scrollPos['scrollLeft'] - ($('div.overlayContainer').width()/2)
			}).show();

			$('#bigAjaxLoader').remove();
			
			omniture.send(lang, region, pageName);
		});
		if($.browser.msie && $.browser.version == 6){
				$('select').hide();
			}
	},
	close : function(){
		// Restart timer
		timer.init();
		
		$('div.overlayContainer').hide().remove();
		if($.browser.msie && $.browser.version == 6){
				$('select').show();
			}
	},
	buildOverlay : function(){
		// Build the content overlay divs
		$('body').append('<div class="overlayContainer"></div>');
	},
	displayLoader : function(){
		ajaxLoader = document.createElement('img')
		$(ajaxLoader).attr({
			'id':'bigAjaxLoader',
			'src':'/web/common/all_languages/all_regions/images/bundles/ajax-loader.gif'
		});
		$(ajaxLoader).css({
			'position':'absolute',
			'top':'50%',
			'left':'50%'
		});
	}
}

bundle = {
  psqtCheck : function(lang, region, campaign, form , controller, method){
		$(form+" #form_psqt_loader").show();
    var params = {}; 
		inputs = $(form).find(" input[@type='hidden'], input[@checked], input[@type='text'], input[@type='password'], input[@type='submit'], option[@selected], textarea").filter(":enabled");
		inputs.each(function(){ 
			params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; 
		});
    
    $.ajax({
			type: "POST",
			url: "/"+lang+"/"+region+"/"+campaign+"/"+controller+"/"+method+".json",
			data: params,
			dataType: "text",
			timeout: 20000,
			success: function(msg) {
        $(form+" #form_psqt_loader").fadeOut();
        $(form+" #form_psqt_inner").remove();
        $(form).append(msg);
			}, 
			error: function(request, error, exception){

			},
			complete: function(object, type){
      
			}
		});
  },
	calculate : function(lang, region, campaign, form , toUpdate){ // bundle
		// Reset timer
		timer.init();
		
		// Closing saving details.
		if ($("#toggleDetail").is(":visible")) {
			toggleDetail.toggle(lang,region);
		};

		var params = {}; 
		inputs = $(form) .find(" input[@type='hidden'], input[@checked], input[@type='text'], input[@type='password'], input[@type='submit'], option[@selected], textarea") 
		.filter(":enabled");
		inputs.each(function() { 
			params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; 
		});

		$.ajax({
			type: "POST",
			url: "/"+lang+"/"+region+"/"+campaign+"/lines_of_business/calculate.json",
			data: params,
			dataType: "text",
			timeout: 20000,
			success: function(msg) {
        $("#form1 #calculator").remove();
        $("#form1").append(msg);
			}, 
			error: function(request, error, exception){

			},
			complete: function(object, type){
				//if the save  features page is called should update the review page
				timer.init();
        $(".error").hide();
        //alert('to calculate');      
				if (toUpdate=="additional_recivers"){
					url_call = "/"+ lang +"/"+ region + "/" + campaign +"/lines_of_business/receivers/?";
					$("#additional_receivers").load(url_call + str.random(),null, function() {
					});
          
				}
				
				// if (toUpdate=="featureCount"){
				// 		url_call = "/"+ lang +"/"+ region + "/" + campaign +"/lines_of_business/update_phone_features.json?";
				// 		$("#featureCount").load(url_call + str.random(),null, function() {
				// 	});
				// }
			}
		});
	}
}



function price(price, lang){
	var ret = "";
	if(lang == 'fr'){
		ret += price.toFixed(2).replace(/\./,",")+'&nbsp;$';
	}else{
		ret += '$'+price.toFixed(2);
	}
	return ret;
}


var identification = {
	selectBox : function(witch) {

	}
}

var toggleId = {
	move : function(caller) {
		if (caller == "MoveOrNot1"){
			$("#newAddress").slideDown()
		}else{
			$("#newAddress").slideUp()
		}
	},
	
	appendContent : function(which, pieceOfId) {
		if($("#OrderPieceOfIdentification1")[0].selectedIndex != $("#OrderPieceOfIdentification2")[0].selectedIndex && ($("#OrderPieceOfIdentification1")[0].selectedIndex != 0 || $("#OrderPieceOfIdentification2")[0].selectedIndex != 0)){
			// Take the selected piece 
			//  id type, and inject it in the correct holder for that type.
			
			if(!$('#' + pieceOfId).html()){
				// If there's no item in the piece holder, insert the selected content.
				$('#' + pieceOfId).append($('#' + which)[0]);
				this.openBlock(which, pieceOfId);
			}else{
				// If there's an item in the piece holder, take the current content, dump it in the general pieces holder
				// and append the new content in the specified holder.
				this.toggleBlock(which, pieceOfId);
			}
		}else{
			this.closeBlock(which, pieceOfId);
		}
	},
	
	openBlock : function(which, pieceOfId) {
		$("#" + pieceOfId + " div:first").hide();
		// Animate the opeing of the div
		$("#" + pieceOfId + " div:first").slideDown(function(){
			toggleId.openParent(which, pieceOfId);
		});
		this.disableOptions(which, pieceOfId);
	},
	
	openParent: function(which, pieceOfId) {
		$('#' + pieceOfId).parent().parent().slideDown();
	},
	
	closeBlock : function(which, pieceOfId) {
		if($("#" + pieceOfId + " div:first")){
			$("#" + pieceOfId + " div:first").slideUp();
			this.disableOptions(which, pieceOfId);
		}
	},
	
	toggleBlock : function(which, pieceOfId) {
	
		$("#" + pieceOfId + " div:first").slideUp(function(){
			$("#piecesOfIdHolder").append($("#" + pieceOfId + " div")[0]);
			$('#' + pieceOfId).append($('#' + which)[0]);
			toggleId.openBlock(which, pieceOfId);
		});
	},
	
	disableOptions : function(which, pieceOfId) {
		if(pieceOfId == "piece1"){
			$('#OrderPieceOfIdentification2 option').each(function(i, el){
				$(el)[0].disabled = false;
				$(el)[0].style.color="#000";
			})
			if($('#OrderPieceOfIdentification1')[0].selectedIndex != 0){
				$('#OrderPieceOfIdentification2')[0].options[$('#OrderPieceOfIdentification1')[0].selectedIndex].disabled = true;
				$('#OrderPieceOfIdentification2')[0].options[$('#OrderPieceOfIdentification1')[0].selectedIndex].style.color="#666";
			}
		}else{
			$('#OrderPieceOfIdentification1 option').each(function(i, el){
				$(el)[0].disabled = false;
				$(el)[0].style.color="#000";
			})
			if($('#OrderPieceOfIdentification2')[0].selectedIndex){
				$('#OrderPieceOfIdentification1')[0].options[$('#OrderPieceOfIdentification2')[0].selectedIndex].disabled = true;
				$('#OrderPieceOfIdentification1')[0].options[$('#OrderPieceOfIdentification2')[0].selectedIndex].style.color="#666";
			}
		}
	},
	
	pageLoad : function(verifyIdentification){
		// Hide the "toggling divs" onload, this way user with javascript disabled will still see them.
		$('.toggleId').each(function(i, el){
			$(el).addClass('toggleDivHidden'); 
		});
		
		$("#creditCardOptions").css('display','block');
		$("#userOtherCreditCard").css('display','block');
		$("#UseCreditCard0").attr('checked','checked');
		
		
		if(verifyIdentification){
			// We need the array with all the values as a default
			piecesArray = new Array();
			piecesArray = $('#OrderPieceOfIdentification1 option');
		
			this.disableOptions('','piece1');
			this.disableOptions('','piece2');
		
			// Reopen the div of the selected pieces of identification
			if($('#OrderPieceOfIdentification1')[0].selectedIndex != 0){
				this.appendContent($('#OrderPieceOfIdentification1')[0].options[$('#OrderPieceOfIdentification1')[0].selectedIndex].value, 'piece1');
			}
			if($('#OrderPieceOfIdentification2')[0].selectedIndex != 0){
				this.appendContent($('#OrderPieceOfIdentification2')[0].options[$('#OrderPieceOfIdentification2')[0].selectedIndex].value, 'piece2');
			}
		}
	}
}


var toggleItem = {
	openBlock : function(caller, el, reversed) {
		var isChecked = (caller && $(caller).parent().parent().find(':radio:first').attr('checked'));
		if(reversed)isChecked = !isChecked;
		if (isChecked){
			$("#" + el).slideUp();
		}else{
			$("#" + el).slideDown();
		}
	}	
}

var accountNumbers = {
	openBlock : function(el, id) {
		if ($(el).is(":checked")) {
			$("#" +id).show();
		} else {
			$("#" + id).hide();
		};
	}
}


var emailSettings = {
	submit : function(lang,region,campaign) {
		$.ajax({
			type: "POST",
			url: "/"+lang+"/"+region+"/"+campaign+"/email-these-settings",
			data: $("#EmailSettings").serialize(),
			timeout: 20000,
			success: function(msg) {
				$(".overlayContainer").html(msg);
			}, 
			error: function(request, error, exeption){
			},
			complete: function(object, type){		
				
			}

		});		
		
	}
}

var str = {
	random: function() {
		var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
		var string_length = 8;
		var randomstring = '';
		for (var i=0; i<string_length; i++) {
			var rnum = Math.floor(Math.random() * chars.length);
			randomstring += chars.substring(rnum,rnum+1);
		}
		
		return randomstring;
	}
	
}

var omniture = {
	send : function(lang, region, pageName) {
		omniturePrefix = "nb:c:bellbundle:";
		
		pageName = omniturePrefix+pageName;
		
		s.pageName = ""+pageName+"("+lang+"-"+region+")";
		s.prop10 = ""+pageName+"";
		void(s.t());
	},
	
	sendEvent : function(linkTrackVars, events, products) {
		s.linkTrackVars = linkTrackVars;
		s.products = products;
		s.events = events;
		s.tl(this,'o');	
	},
	
	sendLeadBubbleDisplayed : function() {
		s.tl(true,'o','nb:c:bellbundle:voken:displayed');
	},
	
	sendLeadBubbleClicked : function() {
		s.eVar16='BUN_SA_200803_MoreWaysToShop_NT_bundlebellca_voken';
		s.linkTrackVars='eVar16';
		s.linkTrackEvents='None';
		s.tl(this,'o','nb:c:bellbundle:voken:clicked');
	}
}

clickToChat = { 
	show : function(lang,region){ 
		// Reset timer 
		timer.stop(); 
		timer.enabled = false; 

		var objOverlay = document.createElement("div"); 
		objOverlay.setAttribute('id','overlay'); 
		objOverlay.onclick = function() { clickToChat.close(); } 
		document.body.appendChild(objOverlay); 

		// Set the overlay size 
		var arrayPageSize = clickToChat.getPageSize(); 
		$('#overlay').css({ 
			'width':arrayPageSize[0], 
			'height':arrayPageSize[1] 
		}) 
		$('#overlay').css({'opacity': 0}) 
		$('#overlay').animate({'opacity':0},'fast'); 

		// Center the call us div 
		var arrayPageScroll = clickToChat.getPageScroll(); 

		var callUsBoxTop = ((arrayPageSize[3]/2) + arrayPageScroll[1]) - 70; 
		var callUsBoxLeft = ((arrayPageSize[2]/2) + arrayPageScroll[0]) - 190; 

		// hide all selects for IE 
		if(jQuery.browser.msie){ 
			$('select').hide(); 
		} 

		$('#lpcttDiv').css({ 
			'position': 'absolute', 
			'top': callUsBoxTop, 
			'left': callUsBoxLeft, 
			'z-index':50000 
		}); 

		$('#lpcttDiv').fadeIn(); 

		// Omniture call 
		omniture.send(lang,region,"C2T:Form"); 
	}, 
	getPageScroll : function() { 
		var xScroll, yScroll; 
			if (self.pageYOffset) { 
				yScroll = self.pageYOffset; 
				xScroll = self.pageXOffset; 
			} else if (document.documentElement && document.documentElement.scrollTop){      // Explorer 6 Strict 
				yScroll = document.documentElement.scrollTop; 
				xScroll = document.documentElement.scrollLeft; 
			} else if (document.body) {// all other Explorers 
				yScroll = document.body.scrollTop; 
				xScroll = document.body.scrollLeft;      
			} 
			arrayPageScroll = new Array(xScroll,yScroll)  
		 return arrayPageScroll; 
	}, 
	getPageSize : function(){ 
		var xScroll, yScroll; 
		if (window.innerHeight && window.scrollMaxY) {   
			xScroll = window.innerWidth + window.scrollMaxX; 
			yScroll = window.innerHeight + window.scrollMaxY; 
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac 
			xScroll = document.body.scrollWidth; 
			yScroll = document.body.scrollHeight; 
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari 
			xScroll = document.body.offsetWidth; 
			yScroll = document.body.offsetHeight; 
		} 
		var windowWidth, windowHeight; 
		if (self.innerHeight) { // all except Explorer 
			if(document.documentElement.clientWidth){ 
					windowWidth = document.documentElement.clientWidth;  
				} else { 
				 	windowWidth = self.innerWidth; 
				} 
				windowHeight = self.innerHeight; 
		}else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode 
				windowWidth = document.documentElement.clientWidth; 
				windowHeight = document.documentElement.clientHeight; 
		} else if (document.body) { // other Explorers 
				windowWidth = document.body.clientWidth; 
				windowHeight = document.body.clientHeight; 
		}        

		// for small pages with total height less then height of the viewport 
		if(yScroll < windowHeight){ 
		        pageHeight = windowHeight; 
		} else {  
		        pageHeight = yScroll; 
		} 

		// for small pages with total width less then width of the viewport 
		if(xScroll < windowWidth){       
		      pageWidth = xScroll;             
		} else { 
		        pageWidth = windowWidth; 
		} 
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)  
		return arrayPageSize; 
	}, 
	close : function(){ 
		$('#lpcttDiv').fadeOut('normal',function(){ 
		$('#overlay').fadeOut('normal',function(){ 
		               $('#overlay').remove(); 
		 //Shoew all select for IE 
		   if(jQuery.browser.msie){ 
		                     $('select').show(); 
		          } 
		   }); 
		}); 
	}
}

var voken = {
	display : function(url) {
		var r_number = Math.random();
		
		$.include(url + "?number="+r_number);
	}
};

var timer = {
	secs : 30,
	defaultSecs : 30,
	showFor : 10,
	timerID : null,
	showForID : null,
	timerIsRunning : false,
	delay : 1000,
	enabled : true,
	element : $("#bubbleArrow"),
	
	init : function(params) {
		return; 
		if (this.enabled) {
			if (params && params.secs) {
				this.defaultSecs = params.secs;
			};
			this.secs = this.defaultSecs;
		
			this.stop();
			this.start();
		};
	},
	
	start : function() {
		if (this.secs == 0) {
			this.stop();
			
			// Here's where you put something useful that's
			// supposed to happen after the allotted time.
			// For example, you could display a message.
			this.showFor = 10;
			this.show();
			this.endWhen();
			
    } else {
			this.status = this.secs;
			this.secs -= this.delay/1000;
			this.timerIsRunning = true;
			this.timerID = self.setTimeout("timer.start();", this.delay);
		}
	},
	
	show : function() {
		var scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
		if ((timer.windowHeight() + scrollTop) > $("#help").offset().top) {
			scrollTop = $("#help").offset().top;
		} else {
			scrollTop = timer.windowHeight() + scrollTop;
		};
		
		$("#bubbleArrow").show("fast", function() {
			$("#bubbleArrow").animate({top: ((scrollTop) - $("#bubbleArrow").height()-10)+"px"});
			
			omniture.sendLeadBubbleDisplayed();
		});
	},
	
	endWhen : function() {
		if (this.showFor == 0) {
			self.clearTimeout(this.showForID);
			this.close();
		} else {
			this.showFor -= this.delay/1000;
			
			this.showForID = self.setTimeout("timer.endWhen();", this.delay);
		};
	},
	
	stop : function() {
		if (this.timerIsRunning) {
			self.clearTimeout(this.timerID);
			this.timerIsRunning = false;
		};
	},
	
	scroll : function(el) {
		omniture.sendLeadBubbleClicked();

		offset = $(el).offset().top;
		
		this.close();
		
		$("html,body").animate({scrollTop:offset - 50},'slow');
		$("#bubbleArrow").animate({top: offset - $("#bubbleArrow").height()}, function() {
			if($.browser.msie) {
				this.style.removeAttribute('filter');	
			}
			$("#help").fadeOut("fast", function() {
				$("#help").fadeIn("fast");
			});
		});
	},

	clickToChat : function(lang,region) { 
		omniture.sendLeadBubbleClicked(); 

		this.close(); 
		clickToChat.show(lang, region); 
	},
	
	close : function() {
		this.enabled = false;
		
		this.hide();
	},
	
	hide : function() {
		$("#bubbleArrow").fadeOut();
	},
	
	windowHeight : function() {
		var myWidth = 0, myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    myWidth = window.innerWidth;
	    myHeight = window.innerHeight;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	    myWidth = document.documentElement.clientWidth;
	    myHeight = document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
	    myWidth = document.body.clientWidth;
	    myHeight = document.body.clientHeight;
	  }
		
		return myHeight;
	}
};

var programming = {
	toggle : function(lang, region, campaign, form) {
		fadeTimer = 200;
		
		// Get the currently selected radio if there's one
		position = 0; // To find the posiiton of the selected element
		$("#OrderProgrammingLanguage").parent().find('ul:visible input[type=radio]').each(function(){
			if($(this).is(":checked")){
				return false;
			}else{
				position ++;
			}
		});
		
		if ($("#OrderProgrammingLanguage option:selected").val() == "fr") {
			$("#prog_en").fadeOut(fadeTimer, function() {
				$("#prog_fr").fadeIn(fadeTimer,function(){
					// Once the switch is done, go in the visible list, select the same radio as selected in the old language
					$("#OrderProgrammingLanguage").parent().find('ul:visible input[id*=ServiceTelevisionId]:eq('+position+')').attr('checked','checked').click();
				});
			})
		} else {
			$("#prog_fr").fadeOut(fadeTimer, function() {
				$("#prog_en").fadeIn(fadeTimer,function(){
					// Once the switch is done, go in the visible list, select the same radio as selected in the old language
					$("#OrderProgrammingLanguage").parent().find('ul:visible input[id*=ServiceTelevisionId]:eq('+position+')').attr('checked','checked').click();
				});
			})
		};
	}
}

/*******  *******/
/*******  *******/
/*******  *******/
/******* FOUND IN POPUP.JS, put here for reducing the number of files as much as possible *******/
/*******  *******/
/*******  *******/
/*******  *******/
function popper(thisUrl, thisWindow, thisWidth, thisHeight, thisTop, thisLeft) {
    optionString = ('width=' + thisWidth + ',height=' + thisHeight + ',top=' + thisTop + ',left=' + thisLeft + ',status=no,menubar=no,resizable=yes,scrollbars=yes');
    mainWin = window.open(thisUrl, thisWindow, optionString);
}


/*******  *******/
/*******  *******/
/*******  *******/
/******* FOUND IN ADDITIONAL.JS, put here for reducing the number of files as much as possible *******/
/*******  *******/
/*******  *******/
/*******  *******/
var custom_var = "NB-"; 
if (typeof s != "undefined") { 
	if(typeof(s.pageName)!="undefined") custom_var += s.pageName; 
}

/*for the -rate this page- link in the header and footer*/
var _sp='%3A\\/\\/',_rp='%3A//',_poE=0.0, _poX=0.0,_sH=screen.height,_d=document,_w=window,_ht=escape(_w.location.href),_hr=_d.referrer,_tm=(new Date()).getTime(),_kp=0,_sW=screen.width;_d.onkeypress=_fK;
function _fK(_e){
    if(!_e)_e=_w.event;
    var _k=(typeof _e.which=='number')?_e.which:_e.keyCode;
    if((_kp==15&&_k==12))_w.open('http://www.opinionlab.com/ozone/24-7.asp?referer='+_fC(_ht),'Report','width=370,height=200,resizable=no,copyhistory=no,scrollbars=no');
    _kp=_k;
}

function _fC(_u){
    _aT=_sp+',\\/,\\.,-,_,'+_rp+',%2F,%2E,%2D,%5F';_aA=_aT.split(',');
    for(i=0;i<5;i++){
        eval('_u=_u.replace(/'+_aA[i]+'/g,_aA[i+5])')
    }
    return _u;
}

function O_LC(){
    _w.open('http://ccc01.opinionlab.com/comment_card.asp?time1='+_tm+'&time2='+(new Date()).getTime()+'&prev='+_fC(escape(_hr))+'&referer='+_fC(_ht)+'&height='+_sH+'&width='+_sW+'&custom_var='+custom_var,'comments','width=535,height=192,screenX='+((_sW-535)/2)+',screenY='+((_sH-192)/2)+',top='+((_sH-192)/2)+',left='+((_sW-535)/2)+',resizable=yes,c=no');
}

function _fPe(){
    if(Math.random()>=1.0-_poE){
        O_LC();
        _poX=0.0;
    }
}

function _fPx(){
    if(Math.random()>=1.0-_poX)O_LC();
}

window.onunload=_fPx;

function O_GoT(_p){
    _d.write('<a href=\'javascript:O_LC()\'>'+_p+'</a>');
    _fPe();
}

//functions for limitation of the calendar
//checks if the year is Leap or not
function LeapYear(year) {
	if ((year/4)   != Math.floor(year/4))   return false;
	if ((year/100) != Math.floor(year/100)) return true;
	if ((year/400) != Math.floor(year/400)) return false;
	return true;
}

//returning the higher day in the month by year and date
//returns 0 if input parameters are not valid integers
function getMonthDays(intYear,intMonth){
	var daysofmonth   = new Array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	var daysofmonthLY = new Array( 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	if (!isNaN(intMonth) && !isNaN(intYear)){
		if (intMonth>0){intMonth--;}

			if (LeapYear(intYear)) {
			  daysofmonth = daysofmonthLY;
			}
			return daysofmonth[intMonth];
	}else{
		return 0;
	}
}


//limits the year select options for the period 
function limitYear(divYear,divMonth,divDay,startOffset, endOffset,disableDates){
	var currentYear = $("select#" + divYear).val();
	today=new Date();
	this_year = today.getFullYear();
	start=new Date(this_year,today.getMonth(), today.getDate() + startOffset);
	end=new Date(this_year,today.getMonth(), today.getDate() + endOffset);
	end_year = end.getFullYear();
	$("select#" + divYear).html('');
	output='<option value=""></option>';
	for (var i=this_year; i < end_year + 1; i++) {
		output=output + '<option value="' +i +'">' + i + '</option>';
	};



	//if the current is in the allowed interval thene preselct it
	$("select#" + divYear).html(output);
  if ((currentYear>=this_year) && (currentYear<=end_year)){
			$("select#" + divYear).val(currentYear);
   }else{
			$("select#" + divYear).val(this_year);
  }




	setDays(divYear,divMonth,divDay,startOffset,endOffset,disableDates);
}

 function in_array( what, where ){
		var a=false;
		for(var i=0;i<where.length;i++){
			if(what == where[i]){
				a=true;
				break;
			}
		}
		return a;
	}



//disables all dates excluding those in the future period defined by start and end Offset
function setDays(divYear,divMonth,divDay,startOffset,endOffset,disableDates){
	//return;
	var intMonth = parseFloat($("select#" + divMonth).val()) ;
	var intYear = parseFloat($("select#" + divYear).val());
	var currentDay =$("select#" + divDay).val();
	var currentMonth =$("select#" + divMonth).val();

	today=new Date();
	this_year = today.getFullYear();
	start=new Date(this_year,today.getMonth(), today.getDate() + startOffset);
	start_year = today.getFullYear();
	start_month = start.getMonth();
	start_month ++;
	start_day = start.getDate();

	end=new Date(this_year,today.getMonth(), today.getDate() + endOffset);
	end_year = end.getFullYear();
	end_month = end.getMonth();
	end_day = end.getDate();
	end_month ++ ;


	var myMonths=['January','February','March','April','May','June','July','August','September','October','November','December'];

	var max_days = getMonthDays(intYear,intMonth);
	// if max days are 0 the specified date is not correct probably
	// year or month is not selected
	
	if (max_days>0){
		//redraws the select if max day is high
		var myDays=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
		output='<option value=""></option>';

		flag =false;
		for (var i=0; i < max_days; i++) {
			day = i ;
			day ++;
			str_day='';
			if (day<10){		
				str_day='0' + day;
			}else{
				str_day=day;
			}
			var tmp_date=new Date(intYear,intMonth -1,day);
			thisDay=tmp_date.getDay();
			//alert(thisDay);
			thisDay=myDays[thisDay];
			if (((thisDay=='Sunday') && in_array('Sunday',disableDates)) || ((thisDay=='Saturday') && in_array('Saturday',disableDates)) || ((intYear==start_year) && (intMonth==start_month) && (day<start_day)) || ((intYear==start_year) && (intMonth<start_month)) ||  ((intYear==end_year) && (intMonth>end_month)) || ((intYear==end_year) && (intMonth==end_month) && (day>end_day))) {
				if (currentDay == day) {
					flag=true;
				}
				output=output + '<option value="' +str_day +'" disabled style="color:#666;">' + day + '</option>';
			}else{
				output=output + '<option value="' +str_day +'"  style="color:#000;" >' + day + '</option>';
			}
		};
		$("select#" + divDay).html(output);
		//have to preselect old day if exist
		//TODO have to slect new date if current is disabled
		if (!flag){
			$("select#" + divDay).val(currentDay);
		}else{
			$("select#" + divDay).val("");
		}
	}
	//have to disable months if year is selected
	 if (!isNaN(intYear)){
			flag=false;
			output='<option value=""></option>'; 
			for (var i=0; i < 12; i++) {
				tmpMonth=i +1;
				if (tmpMonth<10){		
					str_month='0' + tmpMonth;
				}else{
					str_month=tmpMonth;
				}
				if (((intYear==start_year) && (tmpMonth<start_month)) || ((intYear==end_year) && (tmpMonth>end_month))){
					if (tmpMonth==intMonth){
						flag=true;
					}
					output=output + '<option value="' +str_month +'" disabled style="color:#666;" >' + myMonths[i] + '</option>';
				}else{
					output=output + '<option value="' +str_month +'">' + myMonths[i] + '</option>';
				}
			};
			$("select#" + divMonth).html(output);
			if (!flag){ 
			  $("select#" + divMonth).val(currentMonth);
			}else{
				$("select#" + divMonth).val("");
			}
	}

}

getScroll = function() {
	scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
	scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || 0;
	return {scrollTop:scrollTop,scrollLeft:scrollLeft};
}

function popper(thisUrl, thisWindow, thisWidth, thisHeight, thisTop, thisLeft) {
    optionString = ('width=' + thisWidth + ',height=' + thisHeight + ',top=' + thisTop + ',left=' + thisLeft + ',status=no,menubar=no,resizable=yes,scrollbars=yes');
    mainWin = window.open(thisUrl, thisWindow, optionString);
}

provinceSelect = {
	toggle : function(){
		scrollPos = provinceSelect.getScroll();

		$('#bb_provinceSelector').css({
			'top': ($(window).height()/2) + scrollPos['scrollTop'] - ($('#bb_provinceSelector').height()/2),
			'left': ($(window).width()/2) + scrollPos['scrollLeft'] - ($('#bb_provinceSelector').width()/2)
		}).show();
	},
	changeProvince : function(lang) {
		// if we did not select a province, assign the default on the dropdown list
		if(!provinceSelect.provinceToGo){
			provinceSelect.provinceToGo = 'on';
		}
		
		location.href = '/' + lang + '/' + provinceSelect.provinceToGo;
	},
	close : function() {
		$('#bb_provinceSelector').hide();
	},
	getScroll : function(){
		scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
		scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || 0;
		return {scrollTop:scrollTop,scrollLeft:scrollLeft};
	}
}

function showSelected(which) {
	// initial value
	provinceSelect.provinceToGo = 'on';
	var map = document.getElementById('img_mapCanada');
	switch(which){
		case "slt_provinceSelector_input_on":
		map.src = "/web/common/all_languages/all_regions/images/backgrounds/map_canadaOntarioOn.gif"
		provinceSelect.provinceToGo = 'on';
		break;

		case "slt_provinceSelector_input_qc":
		map.src = "/web/common/all_languages/all_regions/images/backgrounds/map_canadaQcOn.gif"
		provinceSelect.provinceToGo = 'qc';
		break;
	}
}

    /* inputs autojump */
    var downStrokeField;
    function autojump(fieldName,nextFieldName,fakeMaxLength)
    {
    var myForm=document.forms[document.forms.length - 1];
    var myField=myForm.elements[fieldName];
    myField.nextField=myForm.elements[nextFieldName];

    if (myField.maxLength == null)
    myField.maxLength=fakeMaxLength;

    myField.onkeydown=autojump_keyDown;
    myField.onkeyup=autojump_keyUp;
    }

    function autojump_keyDown()
    {
    this.beforeLength=this.value.length;
    downStrokeField=this;
    }

    function autojump_keyUp()
    {
    if (
    (this == downStrokeField) && 
    (this.value.length > this.beforeLength) && 
    (this.value.length >= this.maxLength)
    )
    this.nextField.focus();
    downStrokeField=null;
    }





// nouveau popup click to talk


clickToChatBigger = { 
	show : function(lang,region){ 
		// Reset timer 
		timer.stop(); 
		timer.enabled = false; 

		var objOverlay = document.createElement("div"); 
		objOverlay.setAttribute('id','overlay'); 
		objOverlay.onclick = function() { clickToChatBigger.close(); } 
		document.body.appendChild(objOverlay); 

		// Set the overlay size 
		var arrayPageSize = clickToChatBigger.getPageSize(); 
		$('#overlay').css({ 
			'width':arrayPageSize[0], 
			'height':arrayPageSize[1] 
		}) 
		$('#overlay').css({'opacity': 0}) 
		$('#overlay').animate({'opacity':0},'fast'); 

		// Center the call us div 
		var arrayPageScroll = clickToChatBigger.getPageScroll(); 

		var callUsBoxTop = ((arrayPageSize[3]/2) + arrayPageScroll[1]) - 300; 
		var callUsBoxLeft = ((arrayPageSize[2]/2) + arrayPageScroll[0]) - 300; 

		// hide all selects for IE 
		if(jQuery.browser.msie){ 
			$('select').hide(); 
		} 

		$('#livePersonDiv').css({ 
			'position': 'absolute', 
			'top': callUsBoxTop, 
			'left': callUsBoxLeft, 
			'z-index':50000 
		}); 

		$('#livePersonDiv').fadeIn(); 
		
	}, 
	getPageScroll : function() { 
		var xScroll, yScroll; 
			if (self.pageYOffset) { 
				yScroll = self.pageYOffset; 
				xScroll = self.pageXOffset; 
			} else if (document.documentElement && document.documentElement.scrollTop){      // Explorer 6 Strict 
				yScroll = document.documentElement.scrollTop; 
				xScroll = document.documentElement.scrollLeft; 
			} else if (document.body) {// all other Explorers 
				yScroll = document.body.scrollTop; 
				xScroll = document.body.scrollLeft;      
			} 
			arrayPageScroll = new Array(xScroll,yScroll)  
		 return arrayPageScroll; 
	}, 
	getPageSize : function(){ 
		var xScroll, yScroll; 
		if (window.innerHeight && window.scrollMaxY) {   
			xScroll = window.innerWidth + window.scrollMaxX; 
			yScroll = window.innerHeight + window.scrollMaxY; 
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac 
			xScroll = document.body.scrollWidth; 
			yScroll = document.body.scrollHeight; 
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari 
			xScroll = document.body.offsetWidth; 
			yScroll = document.body.offsetHeight; 
		} 
		var windowWidth, windowHeight; 
		if (self.innerHeight) { // all except Explorer 
			if(document.documentElement.clientWidth){ 
					windowWidth = document.documentElement.clientWidth;  
				} else { 
				 	windowWidth = self.innerWidth; 
				} 
				windowHeight = self.innerHeight; 
		}else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode 
				windowWidth = document.documentElement.clientWidth; 
				windowHeight = document.documentElement.clientHeight; 
		} else if (document.body) { // other Explorers 
				windowWidth = document.body.clientWidth; 
				windowHeight = document.body.clientHeight; 
		}        

		// for small pages with total height less then height of the viewport 
		if(yScroll < windowHeight){ 
		        pageHeight = windowHeight; 
		} else {  
		        pageHeight = yScroll; 
		} 

		// for small pages with total width less then width of the viewport 
		if(xScroll < windowWidth){       
		      pageWidth = xScroll;             
		} else { 
		        pageWidth = windowWidth; 
		} 
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)  
		return arrayPageSize; 
	}, 
	close : function(){ 
		$('#livePersonDiv').fadeOut('normal',function(){ 
		$('#overlay').fadeOut('normal',function(){ 
		               $('#overlay').remove(); 
		 //Shoew all select for IE 
		   if(jQuery.browser.msie){ 
		   	$('select:not(#slt_provinceSelector)').show(); 
		   } 
		   }); 
		}); 
	}
}

var bubble_error = {
	open : function(el) {
		

			 var parent =$('div.calculator_error').parent();
			//alert(parent.html);
			 $(parent).append($("#" +el).show());
			 
				if(jQuery.browser.msie){
								 $("#" +el).css({'left':$("#" +el).width()-70,'top':-$("#" +el).height()+30});
				}else{
								 $("#" +el).css({'left':$("#" +el).width()-100,'top':-$("#" +el).height()+30});
					
				}
				
				if(jQuery.browser.msie && jQuery.browser.version == 6) $('select').css('visibility','hidden');

			
	},
	close : function(el) {
		$("#" +el).hide();
		

	}
	
}


var mainReciver = {
	save : function(lang, region, campaign, form) {
			var params = {}; 
			inputs = $(form) .find(" input[@type='hidden'], input[@checked], input[@type='text'], input[@type='password'], input[@type='submit'], option[@selected], textarea") 
			.filter(":enabled");
			inputs.each(function() {
				params[ this.name ] = this.value; 
			});

			var r_number = Math.random();


			$.ajax({
				type: "POST",
				url: "/"+lang+"/"+region+"/"+campaign+"/lines_of_business/check_main_reciver.json?number="+r_number,
				data: params,
				dataType: "json",
				timeout: 20000,
				success: function(msg) {
					output='';
					if (msg.success==true){
						$("#main_receiver").html(label[lang]['main_reciver_label'] + ' ' + label[lang][msg.main_receiver]);
						bundle.calculate(lang, region, campaign, '','');
						$("#mainReciverError").html('');
						$(".error").html('');
						overlay.close();
			
					}else{
						$.each(msg, function(erreur) {
							succes=false;
						//	alert(erreur);
							if (erreur!='success'){
								output += label[lang][msg[erreur]]+'<br/>';
							}
						});

						$("#main_receiver_error").html(output);

					}
				},
				
				complete: function(object,type){	

			  }
				
				
			});	
	}
}



internetInstallation = {
	save : function(lang, region, campaign, form) {
  	var params = {}; 
		inputs = $(form) .find(" input[@type='hidden'], input[@checked], input[@type='text'], input[@type='password'], input[@type='submit'], option[@selected], textarea") 
		.filter(":enabled");
    $(".inputError").hide();
		inputs.each(function(){ params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; });

		$.ajax({
			type: "POST",
			url: "/"+lang+"/"+region+"/"+campaign+"/lines_of_business/check_internet_installation.json",
			data: params,
			dataType: "json",
			timeout: 20000,
			success: function(msg) {
								
				$.each(msg, function(erreur){
					//validation_passed=false;
					//output += msg[erreur]+'<br/>';
				});
				
					bundle.calculate(lang, region, campaign, form, 'additional_recivers');
          url_call = "/"+ lang +"/"+ region + "/" + campaign +"/lines_of_business/internet_installation/?";
					$("#internet_installation").load(url_call + str.random(),null, function() {
					});
					overlay.close();
				
			}, 
			error: function(request, error, exeption){
        
			},
			complete: function(object, type){		
				
			}

		});
  
	}
}

