/* LANGUAGE RESOURCE OBJECT
********************************************************************************************/
function LanguageResource() {
    var self = this;

    /*
    default langage setting is english.
    */
    self.language;
    self.add_label_text;
    self.remove_label_text;
    self.addtocart_label_text;
    self.entersearch_label_text;
    self.enterpostalcode_label_text;
    self.moreplan_label_text;
    self.selectcountry_label_text;
    self.city_label_text;
    self.postalcode_label_text;
    self.backtotop_label_text;
    self.selectcity_label_text;

    self.init = function () {
        var pathArray = $(location).attr('pathname').split('/');
        if (pathArray[1].match('fr|en'))
            self.language = pathArray[1];
        self.setup_labels();
    };

    self.setup_labels = function () {
        if (self.language == 'fr') {
            self.add_label_text = "Ajouter";
            self.remove_label_text = "Enlever";
            self.addtocart_label_text = "Ajouter au panier";
            self.entersearch_label_text = "Que cherchez-vous?";
            self.enterpostalcode_label_text = "Saisissez votre code postal";
            self.moreplan_label_text = "Autres forfaits";
            self.selectcountry_label_text = "Veuillez choisir un pays :";
            self.city_label_text = "Ville...";
            self.postalcode_label_text = "Code postal...";
            self.backtotop_label_text = "Haut de la page";
            self.selectcity_label_text =  "S&eacute;lectionnez votre ville...";
        } else {
            self.add_label_text = "Add";
            self.remove_label_text = "Remove";
            self.addtocart_label_text = "Add to cart";
            self.entersearch_label_text = "Enter your search...";
            self.enterpostalcode_label_text = "Enter your postal code ...";
            self.moreplan_label_text = "More plans";
            self.selectcountry_label_text = "Please select a country:";
            self.city_label_text = "City...";
            self.postalcode_label_text = "Postal code...";
            self.backtotop_label_text = "Back to top";
            self.selectcity_label_text = "Select your city...";
        }
    }
    self.init();
}
var language = new LanguageResource();

/* COOKIE OBJECT  
********************************************************************************************/
function cookie(domain_name) {
  //shortcut for encapsulation
  var self = this;
  
  /*
    Default Variables
  */
  self._domain = (domain_name == null) ? "" : domain_name;
  
  /*
    Getters and setters
  */
  self.setDomain = function (domain_name) {
        self._domain = domain_name;
  }
  self.getDomain =  function() {
      return self._domain;
  }
    
  /*
    initialize the download button based on the specified
    container ID
  */
  self.init = function(domain_name) {
    self._domain = (domain_name == null) ? "" : domain_name;    
  } 
  
  /*
    set a cookie c_name with value that expires in expiredays
  */
  self.setCookie = function(c_name,value,expiredays)
  {
    //function to set a cookie
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    cookie_val = c_name+ "=" +escape(value)+";path=/"+
    ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
	cookie_val = (self._domain.length > 0) ? cookie_val + ";domain="+self._domain : cookie_val;
	document.cookie=cookie_val;
  }
  
  /*
    get the value of c_name cookie
  */
  self.getCookie = function(c_name)
  {
    //function to get a cookie
    if (document.cookie.length>0)
      {
      c_start=document.cookie.indexOf(c_name + "=");
      if (c_start!=-1)
        { 
        c_start=c_start + c_name.length+1; 
        c_end=document.cookie.indexOf(";",c_start);
        if (c_end==-1) c_end=document.cookie.length;
        return unescape(document.cookie.substring(c_start,c_end));
        } 
      }
    return false;
  }
  
  /*
    check to see if cookie cookie_name exists
  */
  self.checkCookie = function(cookie_name)
  {
    //function to check if the cookie exists
    cookie_val=self.getCookie(cookie_name);
    if (cookie_val!=null && cookie_val!="")
    {
      return true;
    }
    else 
    {
      return false;
    }
  }
  self.deleteCookie = function( name, path, domain ) {
    if ( self.getCookie( name ) ) document.cookie = name + "=" +
      ( ( path ) ? ";path=" + path : "") +
      ( ( domain ) ? ";domain=" + domain : "" ) +
      ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
  }

}

/* FIX THE CONTAINER RESIZE ISSUE
********************************************************************************************/
$(window).resize(function()
{
	var window_width = parseInt($(window).width());
	var container_width = parseInt($('#shell').width());
	
	if(window_width < container_width){
		$('#container').css('width',container_width+"px");
		$('#footer_container').css('width',container_width+"px");
	} else {
		$('#container').css('width',"100%");
		$('#footer_container').css('width',"100%");
	}
});


/* SEARCH TEXT REPLACEMENT  
********************************************************************************************/
function SetupWatermarkForTextbox() {
    var self = this;

    self.init = function () {
        var search_input = new InputWaterMark('#search_criteria', language.entersearch_label_text);
        var zone_search_input = new InputWaterMark('#lookup-postalcode', language.enterpostalcode_label_text);
    };
    self.init();
}
var setupWatermarks = new SetupWatermarkForTextbox();



/* SUPPORT LANDING
********************************************************************************************/

function SetupSupport() {
    var self = this;

    self.num_entries = 5;

    self.init = function () {
        if ($('.support_home_list').length > 0) {
            self.setup_home_list();
        }
    }

    self.setup_home_list = function () {
        $('.support_home_list .entry').each(function () {
            if ($(this).find('h5').length > 0) {
                $(this).find('h5').each(function () {
                    //console.log($(this).html() + " | " + $(this).nextUntil('h5').length + " | " + $(this).nextUntil('h5').slice(self.num_entries).length);
                    if ($(this).nextUntil('h5').length > self.num_entries) {
                        $(this).nextUntil('h5').slice(self.num_entries).wrapAll("<div class='support_link_container' />");
                    }
                });
            } else {
                if ($(this).find('a').length > self.num_entries) {
                    $(this).find('a').slice(self.num_entries).wrapAll("<div class='support_link_container' />");
                }
            }
        });

        $('.support_link_container').hide().each(function () {
            $(this).after('<a href="#" title="" class="see_all">See all</a>');
        });

        $('.see_all').unbind('click').click(function () {
            $(this).prev().slideDown();
            $(this).hide();
            return false;
        });
    }

    self.init();
}

//var setup_support = new SetupSupport();

/* SUPPORT Add to Carts (checkboxes
********************************************************************************************/
function SetupAddToCarts() {
    var self = this;

    self.init = function () {
        self.recheck_inputs();
    }

    self.recheck_inputs = function () {
        $('input[name="addonids"]').each(function () {
            if ($(this).attr('checked')) {
                $(this).parent().find('a.btn_add').removeClass('btn_add').addClass('btn_remove').html('Remove');
            } else {
                $(this).parent().find('a.btn_remove').removeClass('btn_remove').addClass('btn_add').html('Add');
                $(this).parent().find('a.process_add ').removeClass('process_add').addClass('process');
            }
        });
        self.setup_links();
    }

    self.setup_links = function () {
        $('.btn_continue').unbind('click').click(function () {
            var popupContainer = $('.AddonSpecificPopupContainer');
            if (popupContainer.length > 0) // if a popup container exists ( if the price is addon specific), check if the specified addon is selected.
            {
                var isDataAddonSelected = false;
                if ($('input[name="addonids"]:checked').length > 0) {
                 $('input[name="addonids"]:checked').each(function () {
                   var addonIdObj = $(this).val();
                    $('input[name="highlightedAddonIds"]').each(function () {
                        var highlightedAddonIdObj = $(this).val();
                        if (addonIdObj == highlightedAddonIdObj) {
                            isDataAddonSelected = true;
                        }
                    });
                });
                }

                if (isDataAddonSelected == false) // if data addon is not selected,
                {
                    setup_overlay.show_sml('.AddonSpecificPopupContainer'); // show a dialog box
                    return false;
                }
                else { // if data add on is selected, process the form
                    $(this).parents('form').submit();
                    return false;
                }
            }
            else {
                $(this).parents('form').submit();
                return false;
            }
        });
        $('.btn_add.process').unbind('click').click(function () {
            var current_class = $(this).attr('class').replace('btn_add', '').replace('process', '').replace("  ", " ");
            /*
            $(this).parent().children('input').attr('checked', 'checked');		
            $(this).replaceWith('<a href="#" class="btn_remove process_add ' + current_class + '">Remove</a>');
            */
            self.filter_addons($(this), current_class);
            self.setup_links();
            return false;
        });

        $('.btn_remove.process_add').unbind('click').click(function () {
            $(this).parent().children('input').attr('checked', '');
            var current_class = $(this).attr('class').replace('btn_remove', '').replace('process_add', '').replace("  ", " ");
            $(this).replaceWith('<a href="#" class="btn_add process ' + current_class + '">' + language.add_label_text + '</a>');
            self.setup_links();
            return false;
        });

        $('.accessory_description .btn_add_to_cart.grey.process').unbind('click').click(function () {
            $(this).parent().children('input').attr('checked', 'checked');
            $(this).replaceWith('<a href="#" class="btn_remove process_add_to_cart">' + language.remove_label_text + '</a>');
            self.setup_links();
            return false;
        });

        $('.btn_remove.process_add_to_cart').unbind('click').click(function () {
            $(this).parent().children('input').attr('checked', '');
            $(this).replaceWith('<a href="#" class="btn_add_to_cart grey process">' + language.addtocart_label_text + '</a>');
            self.setup_links();
            return false;
        });
    }
	
	self.filter_addons = function(obj,classnames){
		var current_classes = classnames.split(' ');
		
		$('.btn_remove.process_add').each(function(){
			for(var x =0; x< current_classes.length;x++){
				if($(this).attr('class').indexOf(current_classes[x]) > 0 && current_classes[x].length > 2){
	         		$(this).parent().children('input').attr('checked', '');
					var current_class = $(this).attr('class').replace('btn_remove','').replace('process_add','').replace("  "," ");
					$(this).replaceWith('<a href="#" class="btn_add process ' + current_class + '">' + language.add_label_text + '</a>');
				}
			}
		});

        $(obj).parent().children('input').attr('checked', 'checked');
        $(obj).replaceWith('<a href="#" class="btn_remove process_add ' + classnames + '">' + language.remove_label_text + '</a>');
        self.setup_links();
	}

    self.init();
}

var setup_add_to_carts = new SetupAddToCarts();

/* Setup Filter Tips
********************************************************************************************/
function SetupFilterTips() {
    var self = this;
    self.offset = 5;
    self.feature_class = "";
    self.plan_class = "";

    self.init = function () {

        $('#plan-options a').unbind('click').click(function () {
            $('#plan-options a').removeClass('active');
            self.plan_class = $(this).attr('class');
            $(this).addClass('active');

            self.show_only_phones();
            return false;
        });

        $('#phone-features a').unbind('click').click(function () {
            $(this).toggleClass('active');
            self.show_only_phones();
            return false;
        });
        $('#phone-features a').unbind('mouseover').mouseover(function () {
            self.setup_tip($(this));
        });
        $('#phone-features a').unbind('mouseout').mouseout(function () {
            self.close_tip();
        });

        $('.phone_icons li').unbind('mouseover').mouseover(function () {
            self.setup_tip($(this));
        });
        $('.phone_icons li').unbind('mouseout').mouseout(function () {
            self.close_tip();
        });

        $('.phone_icons span').unbind('mouseover').mouseover(function () {
            self.setup_tip($(this));
        });
        $('.phone_icons span').unbind('mouseout').mouseout(function () {
            self.close_tip();
        });

        $('.main_content .phone a.learn_more').click(function () {
            if ($(this).parents('.phone').hasClass('disabled')) {
                return false;
            } else {
				if($(this).parents('.phone_info').length > 0){
                	var phone_cookie = new cookie();
					var phone_agreement = $(this).parent().parent().find('.phone_prices .active').attr('class').replace('active', '').replace('price','').replace(" ", '');
	                phone_cookie.setCookie("phone_agreement", phone_agreement, 1);
				}
            }
        });

        $('.main_content .phone input').click(function () {
            if ($(this).parents('.phone').hasClass('disabled')) {
                return false;
            }
        });

        self.show_all_phones();
    }

    self.show_all_phones = function () {
        $('.main_content .phone').fadeTo('fast', 1.0);
    }


    self.show_only_phones = function () {
		var find_feature = [];
		$('.filter_by_feature .active').each(function(){
			find_feature.push($(this).attr('class').replace('active','').replace(' ',''));
		});
		
        $('.main_content .phone').each(function () {
            var feature_found = false;
            var find_plan = (self.plan_class.length > 0) ? $(this).find(".price." + self.plan_class).length > 0 : true;

            if (self.plan_class.length > 0) {
                $(this).find(".price.active").removeClass('active');
                $(this).find(".price").hide();
                $(this).find(".price." + self.plan_class).addClass('active');
                $(this).find(".price.active").show();
            }

			for(var i in find_feature){
				if($(this).find('.phone_icons .'+find_feature[i]).length > 0){
					feature_found = true;
				}else {
					feature_found = false;
				}
			}
			
			if(find_feature.length == 0){
				feature_found = true;
			}

            if (find_plan && feature_found) {
                $(this).removeClass('disabled');
                $(this).fadeTo('fast', 1.0);
            } else {
                $(this).addClass('disabled');
                $(this).fadeTo('fast', 0.2);
            }
        });
    }
    
    self.setup_tip = function (obj) {
        var top = $(obj).offset().top;
        var left = parseInt($(obj).offset().left) + Math.round(parseInt($(obj).width()) / 2);
        var content = $(obj).html();
        self.close_tip();


        $('body').append("<div class='filter_tip'><span>" + content + "</span></div>");

        top = top - (parseInt($('.filter_tip').height()) + self.offset);
        left = left - Math.round(parseInt($('.filter_tip').width()) / 2);
        $('.filter_tip').css('top', top);
        $('.filter_tip').css('left', left);
        $('.filter_tip').show();
    }

    self.close_tip = function () {
        $('.filter_tip').remove();
        return false;
    }

    self.init();
}

var setup_filter_tips = new SetupFilterTips();

/* PHONE COMPARE
********************************************************************************************/
function SetupComparePhones() {
    var self = this;
    self.compare_url = '/en/Phones/Compare';

    self.init = function () {
        if ($('.phone').length > 1) {
            $('.phone .compare input').attr('checked', '');
            self.setup_compare();
        }
		if($('.compare_table').length > 0){
			self.setup_compare_table();
		}
    }
	self.setup_compare_table = function(){
		$('.compare_table ul').each(function(){
			$(this).find('li').css('height','auto');
			var li_height = 0;
			$(this).find('li').each(function(){
				if(parseInt($(this).height()) > li_height){
					li_height = parseInt($(this).height());
				}/*
				var content = $(this).html();
				$(this).html("<span class='compare_content' style='float: left; width: 100%; text-align: center;'>"+content+"</span>");*/
			});
			if($(this).parents('.tooltip').length == 0){
				$(this).find('li').css('height', li_height + 'px');
			}
			/*
			$(this).find('li').each(function(){
				var li_height = parseInt($(this).height());
				var content_height = parseInt($(this).find('.compare_content').height());
				if(content_height < li_height){
					var difference = Math.round((li_height - content_height) / 2);
					$(this).find('.compare_content').css('padding',difference + 'px 0 0 0');
				}
			});
			*/
		});
	}

    self.setup_compare = function () {
        $('.phone .compare input').click(function () {
            if ($(this).parents('.phone.compared').length == 0 && $('.phone.compared').length < 3) {
                $(this).parents('.phone').append('<div class="compare_overlay"><a href="#" class="btn_compare">Compare</a></div>');
                $(this).parents('.phone').addClass('compared');
                $(this).parents('.phone').find('img').fadeTo('fast', 0.2);
                $(this).parents('.phone').find('.rounded_box').fadeTo('fast', 0.2);
                self.setup_compare_btns();
            } else {
                $(this).parents('.phone').find('.compare_overlay').remove();
                $(this).parents('.phone').removeClass('compared');
                $(this).parents('.phone').find('img').fadeTo('fast', 1);
                $(this).parents('.phone').find('.rounded_box').fadeTo('fast', 1);
            }
			if($(this).parents('.phone.compared').length == 0 && $('.phone.compared').length >= 3){
				return false;
			}
        });
    }

    self.setup_compare_btns = function () {
        $('.phone .btn_compare').unbind('click').click(function () {
            $(this).parents('form').submit();
            return false;
        });
    }

    self.init();
}

var setup_compare_phones = new SetupComparePhones();

/* Setup Plan Listing
********************************************************************************************/
function SetupPlanListing() {
    var self = this;

    self.plan_cutoff = 5;
    self.extra_plans = 0;
    self.num_plans = $('#plan_container .column').length;
    self.plan_width = 0;
    self.offset = 208;
    self.start_position = 0;
    self.btn_margin = 0;
    self.column_height = 0;
	self.animating = false;
	self.padding = 10;
	self.price_offset = 14;
	self.price_offset_fr = 5;

	self.init = function () {
	    self.setup_row_heights();

	    if ($('#plan_container .column.selected').length == 0) {
	        $('#plan-continue').addClass('disabled');
	        $('#plan-continue').fadeTo('fast', 0.5);
	        $('#plan-continue').click(function () {
	            if ($(this).hasClass('disabled')) {
	                return false;
	            }

	        });
	    }
	    self.setup_plan_select();
	    self.setup_content_top_margin();
	}

    self.setup_row_heights = function () {
        var num_rows = $('#pick_your_plan .table .column.first .row').length;
        $('#pick_your_plan .table .row').css('height', 'auto');
        for (x = 0; x < num_rows; x++) {
            row_height = 0;
            $('#pick_your_plan .table .column').each(function () {
                if (parseInt($(this).children('.row:eq(' + x + ')').height()) > row_height) {
                    row_height = parseInt($(this).children('.row:eq(' + x + ')').height());
                }
            });
            if (x == 0 && !($('.table.unlimited_talk').length > 0) && !($('.table.limited_time_offers').length > 0)) {
                if (language.language == "fr") { //different height offset for french
                    row_height = parseInt(row_height) - parseInt(self.price_offset_fr);
                } else {
                    row_height = parseInt(row_height) - parseInt(self.price_offset);
                }
            }
            $('#pick_your_plan .table .column').each(function () {
                $(this).children('.row:eq(' + x + ')').css('height', row_height + 'px');
                $(this).children('.row:eq(' + x + ')').css('padding-top', self.padding + 'px');
                $(this).children('.row:eq(' + x + ')').css('padding-bottom', self.padding + 'px');
            });
            self.column_height += row_height + (self.padding * 2);
        }
        var column_height = parseInt($('#plan_container .column:first').height());
        if (self.num_plans > self.plan_cutoff) {
            self.plan_width = Math.round(parseInt($('#plan_shell').width()) / self.plan_cutoff);
            self.extra_plans = self.num_plans - self.plan_cutoff;
            self.start_position = 0; // Math.ceil(self.extra_plans / 2) * self.plan_width;

            $('#plan_container').css('height', parseInt($('#plan_container .column').css('height')) + 'px');
            $('#plan_shell').css('height', parseInt($('#plan_container .column').css('height')) + 'px');

            $('#plan_container').css('left', '-' + self.start_position + 'px');
            $('#plan_container .column').css('width', self.plan_width + 'px');
            $('#plan_container .column .row').css('width', '100%');
            $('#plan_container').css('width', (self.plan_width * self.num_plans) + "px");
            $('#plan_shell').after("<div class='column_nav'><a href='#' class='next'>Next</a><a href='#' class='prev'>Previous</a><p>" + language.moreplan_label_text + "</p><a href='#' class='next'>Next</a><a href='#' class='prev'>Previous</a></div>");
            $('.column_nav p').css('height', (column_height - self.offset) + 'px');

            self.btn_margin = 0; //Math.floor((parseInt($('#plan_container .column .row.last').width()) - parseInt($('#plan_container .column .row.last a').width())) / 2);

            if (location.hash.length > 0) {
                var tmp_history = location.hash.replace("#", '');
                if (tmp_history.split('|').length > 1) {
                    tmp_history = tmp_history.split('|');
                    for (x = 0; x < tmp_history.length; x++) {
                        if ($('#plan_container .column.' + tmp_history[x]).length > 0) {
                            var new_left = 0 - parseInt($('#plan_container .column.' + tmp_history[x]).index() * self.plan_width);
                            var old_left = parseInt($('#plan_container').css('left'));

                            if (new_left > old_left) {
                                $('#plan_container').css('left', new_left + 'px');
                            } else {
                                if (new_left < (0 - (self.plan_width * (self.num_plans - self.plan_cutoff)))) {
                                    new_left = 1 - (self.plan_width * (self.num_plans - self.plan_cutoff));
                                    $('#plan_container').css('left', new_left + 'px');
                                } else {
                                    $('#plan_container').css('left', new_left + 'px');
                                }
                            }
                            break;
                        }
                    }
                } else {
                    if ($('#plan_container .column.' + tmp_history).length > 0) {
                        var new_left = 0 - parseInt($('#plan_container .column.' + tmp_history).index() * self.plan_width);
                        var old_left = parseInt($('#plan_container').css('left'));

                        if (new_left > old_left) {
                            $('#plan_container').css('left', new_left + 'px');
                        } else {
                            if (new_left < (0 - (self.plan_width * (self.num_plans - self.plan_cutoff)))) {
                                new_left = 1 - (self.plan_width * (self.num_plans - self.plan_cutoff));
                                $('#plan_container').css('left', new_left + 'px');
                            } else {
                                $('#plan_container').css('left', new_left + 'px');
                            }
                        }
                    }
                }
            }

            self.setup_plan_scroll();
        } else {
            $('#plan_container').css('width', "585px");
            $('#plan_shell').css('width', '585px');
            $('#plan_shell').css('height', column_height + 'px');
            $('#plan_container').css('height', column_height + 'px');
        }
    }

    self.setup_plan_select = function () {

        $('#plan_container .btn_add').unbind('click').click(function () {
            if ($(this).hasClass('disabled')) {
                return false;
            }
            $('#plan_container .btn_remove').each(function () {
                var tmp_id = $(this).attr('href').replace("#", '');
                $(this).replaceWith('<a href="#' + tmp_id + '" class="btn_add" title="+ ' + language.add_label_text + '">' + language.add_label_text + '</a>');
            });
            $('#plan_container .column').removeClass('selected');
            $('#plan-continue').removeClass('disabled');
            $('#plan-continue').fadeTo('fast', 1);
            $(this).parents('.column').addClass('selected');
            var plan_id = $(this).attr('href').replace("#", '');
            $('#planid').attr('value', plan_id);
            $(this).replaceWith('<a href="#' + plan_id + '" class="btn_remove" title="- ' + language.remove_label_text + '">' + language.remove_label_text + '</a>');
            self.setup_plan_select();
            return false;
        });
        $('#plan_container .btn_remove').unbind('click').click(function () {
            $('#plan_container .column').removeClass('selected');

            $('#plan-continue').addClass('disabled');
            $('#plan-continue').fadeTo('fast', 0.5);

            $('#plan_id').attr('value', '');
            var tmp_id = $(this).attr('href').replace("#", '');
            $(this).replaceWith('<a href="#' + tmp_id + '" class="btn_add" title="+ Add">Add</a>');
            //$(this).replaceWith('<a href="#" class="btn_add" title="+ Add">Add</a>');
            self.setup_plan_select();
            return false;
        });
        if ($('#pick_your_plan.unlimited_talk').length == 0) {
            $('#plan_container .btn_add').css('margin-left', self.btn_margin + 'px');
            $('#plan_container .btn_remove').css('margin-left', self.btn_margin + 'px');
        } else {

            $('.column.plan select').change(function () {
                if ($(this).children('option:selected').val().length == 0) {
                    if ($(this).parents('.plan').find('.btn_remove').length > 0) {
                        $(this).parents('.plan').find('.btn_remove').replaceWith('<a href="#" class="btn_add" title="+ ' + language.add_label_text + '">' + language.add_label_text + '</a>');
                        $('#planid').attr('value', '');
                        $('#plan_container .column').removeClass('selected');
                        $('#plan-continue').addClass('disabled');
                        $('#plan-continue').fadeTo('fast', 0.5);
                        self.setup_plan_select();
                    }
                    $(this).parents('.plan').find('.btn_add').fadeTo('fast', 0.5);
                    $(this).parents('.plan').find('.btn_add').addClass('disabled');
                } else {
                    $('#zoneid').attr('value', $(this).children('option:selected').val());
                    $(this).parents('.plan').find('.btn_add').fadeTo('fast', 1);
                    $(this).parents('.plan').find('.btn_add').removeClass('disabled');
                }
            });
            $('#plan_container .btn_add').each(function () {
                if ($(this).parents('.column').find('select').length > 0) {
                    if ($(this).parents('.column.plan').find('select').val().length == 0) {
                        $(this).fadeTo('fast', 0.5);
                        $(this).addClass('disabled');
                    } else {
                        $(this).fadeTo('fast', 1);
                        $(this).removeClass('disabled');
                    }
                }
            });
        }
    }

    self.setup_plan_scroll = function () {
		$('.column_nav .prev').addClass('disabled');
        $('.column_nav .next').unbind('click').click(function () {
            var tmp = 0 - (self.extra_plans * self.plan_width);
            var current_left = parseInt($('#plan_container').css('left'));

            $('.column_nav .next').removeClass('disabled');

            if (tmp < current_left) {
				if(!self.animating){
					self.animating = true;
                	$('.column_nav .prev').removeClass('disabled');
                	$('#plan_container').animate({ left: (current_left - self.plan_width) + 'px' },'fast', function(){ self.animating = false; });
					if((current_left - self.plan_width) <= tmp){
						$('.column_nav .next').addClass('disabled');
					}
				}
            }
            if (tmp >= parseInt($('#plan_container').css('left'))) {
                $('.column_nav .next').addClass('disabled');
            }
            return false;
        });
        $('#pick_your_plan .column_nav .prev').unbind('click').click(function () {
            var current_left = parseInt($('#plan_container').css('left'));
            $('.column_nav .prev').removeClass('disabled');

            if (0 > current_left) {
				if(!self.animating){
					self.animating = true;
                	$('.column_nav .next').removeClass('disabled');
                	$('#plan_container').animate({ left: (current_left + self.plan_width) + 'px' },'fast', function(){ self.animating = false; });
					if((current_left + self.plan_width) <= 0){
						$('.column_nav .prev').addClass('disabled');
					}
				}
            }

            if (0 <= parseInt($('#plan_container').css('left'))) {
                $('.column_nav .prev').addClass('disabled');
            }
            return false;
        });
    }

    //add top margin to the content ( <span></span> in the column div) to make it's vertical align centre.
    self.setup_content_top_margin = function () {
        $('.table .column > div').not('.price').each(function () {
            var td_height = parseInt($(this).css('height'));
            var td_top_padding = parseInt($(this).css('padding-top'));
            var child_content = $(this).find('span');
            var child_content_height = parseInt(child_content.height());
            var child_content_top_margin = td_height / 2 - child_content_height / 2;
            if (($.browser.msie) && ($.browser.version < 8)) {
                child_content_top_margin += td_top_padding;
            }
            child_content.css('margin-top', child_content_top_margin + 'px');
        });
    }

    self.init();
}

var setup_plan_listing = new SetupPlanListing();

/* Setup Phone Variants
********************************************************************************************/
function SetupPhoneVariants() {
    var self = this;

    self.init = function () {
        if ($('#detail_box .phone_variants').length > 0) {
            self.setup_variants();
            $('.btn_add_to_cart').unbind('click').click(function () {
                $(this).parents('form').submit();
                return false;
            });
        }

        if ($('.phone_images_more a').length > 0) {
            self.setup_alt_images();
        }
    }

    self.setup_alt_images = function () {
        $('.phone_images_more a').unbind('click').click(function () {
            var show_index = $(this).index();
            $("#phone_images .phone_images_more a").removeClass('active');
            $("#phone_images .phone_images_more a:eq("+show_index+")").addClass('active');

            $('#phone_images .phone_img').hide();
			
            $("#phone_images .group").each(function(){
            	$(this).find(".phone_img:eq(" + show_index + ")").show();
			});
            return false;
        });
    }

    self.setup_variants = function () {
        $('#detail_box .phone_variants input:checked').each(function(){
			$(this).parent().addClass('active');
		});
        $('#detail_box .phone_variants .colour').click(function () {
            var variant = $(this).attr('class').replace('colour', '').replace(' ', '');
			$('#detail_box .phone_variants .active').removeClass('active');
			$(this).addClass('active');
			$('#detail_box .phone_variants input').attr('checked','');
			$(this).parent().find('input').attr('checked','checked');
            $('#phone_images .group').hide();
            $('#phone_images .group.' + variant).show();
			return false;
        });

    }

    self.init();
}

var setup_phone_variants = new SetupPhoneVariants();

/* "I" tips
********************************************************************************************/
function SetupTips() {
    var self = this;
    self.offset = 10;
    self.offset_bottom = 25;

    self.init = function () {
        $('.tooltip').unbind('mouseover').mouseover(function () {
            self.setup_tip($(this));
        });
        $('.tooltip').unbind('mouseout').mouseout(function () {
            self.close_tip();
        });
        $('.site_tip').unbind('mouseover').mouseover(function () {
            self.setup_tip($(this));
        });
        $('.site_tip').unbind('mouseout').mouseout(function () {
            self.close_tip();
        });

        /*
        $('.zone_tip').unbind('mouseover').mouseover(function () {
        self.setup_tip($(this));
        });
        $('.zone_tip').unbind('mouseout').mouseout(function () {
        self.close_tip();
        });*/
    }


    self.setup_tip = function (obj) {
        var top = $(obj).offset().top;
        var left = $(obj).offset().left;
        var content = $(obj).html();
        self.close_tip();
        if (content.toLowerCase().indexOf('<ul') > 0 || content.toLowerCase().indexOf('<div') > 0 || content.toLowerCase().indexOf('<p>') > 0) //chk to see if there are block elements. if so, don't wrap with P tag.
        {
            $('body').append("<div class='tool_tip'><div class='tip_container'><div class='tip'>" + content + "</div></div></div>");
        }
        else {
            $('body').append("<div class='tool_tip'><div class='tip_container'><div class='tip'><p>" + content + "</p></div></div></div>");
        }
        top = top - (parseInt($('.tool_tip').height()) + self.offset);
        $('.tool_tip').css('top', top);
        $('.tool_tip').css('left', left);
        $('.tool_tip').show();

        $('.tool_tip .close').unbind('click').click(function () {
            self.close_tip();
            return false;
        });
    }

    self.close_tip = function () {
        $('.tool_tip').remove();
        return false;
    }

    self.init();
}

var setup_tips = new SetupTips();



/* ROUNDED FORM FIELDS
********************************************************************************************/
function SetupRoundedFields() {
    var self = this;

    self.init = function () {
        $('input.text').each(function () {
            $(this).wrap('<span class="field_left"><span class="field_right"/></span>');
            if (parseInt($(this).css('margin-right')) > 0) {
                var tmp = parseInt($(this).css('margin-right'));
                $(this).css('margin-right', '0');
                $(this).parents('.field_left').css('margin-right', tmp + 'px');
            }
        });
    }

    self.init();
}

var setup_rounded_fields = new SetupRoundedFields();


/* ROUNDED FORM FIELDS
********************************************************************************************/
function SetupHalfColumns() {
    var self = this;

    self.init = function () {
        if ($('.half_size').length > 0) {
            self.adjust_column_height();
        }
    }

    self.adjust_column_height = function () {
        var height1 = parseInt($('.half_size .box_container:first').height());
        var height2 = parseInt($('.half_size .box_container:last').height());

        if (height1 != height2) {
            if (height1 > height2) {
                $('.half_size .box_container:first').css('height', height1 + 'px');
                $('.half_size .box_container:last').css('height', height1 + 'px');
            } else {
                $('.half_size .box_container:last').css('height', height2 + 'px');
                $('.half_size .box_container:first').css('height', height2 + 'px');
            }
        }
    }

    self.init();
}

var setup_half_columns = new SetupHalfColumns();

/* Setup TABS
********************************************************************************************/
function SetupTabs() {
    var self = this;
    self.tabs = [];
    self.tabContainers = [];
	self.current_tab = "";
	self.timer = null;
	self.current_tab = "";
    self.init = function () {

        $('.tabs a').each(function () {
            self.tabs.push(this);
            self.tabContainers.push($(this.hash.replace('#', '.') + '_content').get(0));
        });

        $(self.tabContainers).hide();
        $(self.tabContainers[0]).show();
        $(self.tabs[0]).addClass('active');

        $(self.tabs).click(function () {
            self.tab_click(this);
            return false;
        });
		self.timer = setInterval(function(){ self.check_history(); }, 500);
    }
    self.check_history = function () {

        if (location.hash.length > 0) {
            var tmp_history = location.hash.replace("#", '');
            if (tmp_history.split('|').length > 1) {
                tmp_history = tmp_history.split('|');
                if (tmp_history != self.current_tab) {
                    for (x = 0; x < tmp_history.length; x++) {
                        self.show_tab(tmp_history[x]);
                    }
                    self.current_tab = tmp_history;
                }
            } else {
                if (tmp_history != self.current_tab) {
                    self.show_tab(tmp_history);
                    self.current_tab = tmp_history;
                }
            }
        }
    }
    self.tab_click = function (obj) {
		if(self.current_tab != obj.hash && obj.hash.length > 1){
 		       self.show_tab(obj.hash.replace('#', ''));
				self.current_tab = obj.hash;
		        location.hash = obj.hash;
		}
    }
    self.hide_tabs = function () {
        $(self.tabContainers).hide();
        $(self.tabs).removeClass('active');
    }

    self.show_tab = function (tab_name) {
        if ($("." + tab_name + '_content').length > 0) {
            // hide all tabs
            self.hide_tabs();

            //show only this tab
            $("." + tab_name + '_content').show();
            //setup the history object
            // set up the selected class
            $("." + tab_name + '_tab').addClass('active');
        }
    }

    self.init();
}

var setup_tabs = new SetupTabs();

/* Setup input watermarks
********************************************************************************************/
function InputWaterMark(obj_id, text) {
    var self = this;
    self.input_id = obj_id;
    self.watermark = text;

    self.init = function () {
        $(self.input_id).attr("value", self.watermark);
        $(self.input_id).focus(function () {
            if ($(this).attr("value") == self.watermark)
                $(this).attr("value", "");
        });
        $(self.input_id).blur(function () {
            if ($(this).attr("value") == "")
                $(this).attr("value", self.watermark);
        });
    }

    self.init();
}


/* Setup Maps
********************************************************************************************/
var map = null;
var geocoder = null;

function SetupZoneMap() {
    var self = this; 
    var infoCase = new Array();

    self.zone_url = '/en/ajax/getzoneid';
    URLDomain = "http://www.solomobile.ca";
    self.kmlLayer = null;
    self.markers = new Array();
    self.marker_url = "/en/StoreLocator/AjaxFindStores";
    self.locations = null;
    self.lat = null;
    self.long = null;
    self.mapLayerToggle = 0; //intialize to now show.
    self.mapID = 0;
    self.markers_visible = false;
    self.img_base_url = "/images/store-locator/marker-logos/";
    self.kml_base_url = '/lib/data/';// '/lib/data/';
    //self.lang = "en";


    self.init = function () {
        if ($('.zone_coverage').length > 0) {
            $('.zone_links a').unbind('click').click(function () {
                self.show_zone($(this).attr('href').replace('#', ''));
                return false;
            });

            $('.btnSubmitGo').unbind('click').click(function () {
                self.get_zone($('#lookup-postalcode').attr('value'));
                return false;
            });
            $('.zone_coverage').append("<br class='clear' />");
            $('.zone_coverage').after("<br class='clear' />");

            $('.toggle_markers').unbind('click').click(function () {
                if (self.markers_visible) {
                    if (language.language == "en")
                        $(this).text('Show Store Locations');
                    else
                        $(this).text('Montrer les emplacements des magasins');
                } else {
                    if (language.language == "en")
                        $(this).text('Hide Store Locations');
                    else
                        $(this).text('Cacher les emplacements des magasins');
                }
                if (google.maps.Map.prototype.markers.length > 0) {
                    self.toggleMarkers();
                } else {
                    self.get_locations();
                }
                return false;
            });

            google.maps.Map.prototype.markers = new Array();

            google.maps.Map.prototype.addMarker = function (marker) {
                this.markers[this.markers.length] = marker;
            };

            google.maps.Map.prototype.getMarkers = function () {
                return this.markers
            };

            google.maps.Map.prototype.clearMarkers = function () {
                for (var i = 0; i < this.markers.length; i++) {
                    this.markers[i].setMap(null);
                }
                this.markers = new Array();
            };
        }
    }

    self.get_zone = function (postal_code) {
        var postal = postal_code.replace(" ", '').replace("-", '');
        $.getJSON(self.zone_url, { postalcode: postal }, function (json) {
            if (json.zoneid > 0) {
                self.show_zone(json.zoneid);
            }
        });
    }

    self.show_zone = function (zone_id) {
		self.setup_loader();
		self.set_centerpoint(zone_id);

        switch (parseInt(zone_id)) {
            case 1:
                self.kmlLayer = new google.maps.KmlLayer(URLDomain + self.kml_base_url + 'c.xml' + '?cache=' + (new Date()).getTime(), { preserveViewport: true, suppressInfoWindows: true });
                self.kmlLayer.setMap(map);
                break;
            case 2:

                self.kmlLayer = new google.maps.KmlLayer(URLDomain + self.kml_base_url + 'e.xml' + '?cache=' + (new Date()).getTime(), { preserveViewport: true, suppressInfoWindows: true });
                self.kmlLayer.setMap(map);
                break;
            case 3:
                self.kmlLayer = new google.maps.KmlLayer(URLDomain + self.kml_base_url + 'm.xml' + '?cache=' + (new Date()).getTime(), { preserveViewport: true, suppressInfoWindows: true });
                self.kmlLayer.setMap(map);
                break;
            case 4:
                self.kmlLayer = new google.maps.KmlLayer(URLDomain + self.kml_base_url + 'o.xml' + '?cache=' + (new Date()).getTime(), { preserveViewport: true, suppressInfoWindows: true });
                self.kmlLayer.setMap(map);
                break;
            case 6:
                self.kmlLayer = new google.maps.KmlLayer(URLDomain + self.kml_base_url + 't.xml' + '?cache=' + (new Date()).getTime(), { preserveViewport: true, suppressInfoWindows: true });
                self.kmlLayer.setMap(map);
                break;
            case 7:
                self.kmlLayer = new google.maps.KmlLayer(URLDomain + self.kml_base_url + 'v.xml' + '?cache=' + (new Date()).getTime(), { preserveViewport: true, suppressInfoWindows: true });
                self.kmlLayer.setMap(map);
                break;
            default:
                self.kmlLayer = null;
                break;
        }  
		google.maps.event.addListenerOnce(self.kmlLayer, "metadata_changed", function() {
		    // Best results using this listener and getDefaultViewport
		    self.kmlLayer.bounds = this.getDefaultViewport();
			self.close_loader();
		});


    };
	self.setup_loader = function(){
		$('.zone_desc .btnSubmitGo').parent().append("<img src='/images/loader.gif' height='23' width='23' alt='Loading...' id='map_loader' style='float: left; margin-left: 20px;' />");
	}
	self.close_loader = function(){
		$('#map_loader').remove();
	}
    self.get_centerpoint = function (zone_id) {
        var id = parseInt(zone_id);
        var myLatlng = { 'lat': 0, 'lng': 0, 'zoom': 10 }
        switch (id) {
            case 1:
                myLatlng = { 'lat': 51.042203393026064, 'lng': -114.05593872070312, 'zoom': 10 };
                break;
            case 2:
                myLatlng = { 'lat': 53.54561163101498, 'lng': -113.479156, 'zoom': 10 };
                break;
            case 3:
                myLatlng = { 'lat': 45.51019654498558, 'lng': -73.55484008789062, 'zoom': 9 };
                break;
            case 4:
                myLatlng = { 'lat': 45.42014226680116, 'lng': -75.70198059082031, 'zoom': 9 };
                break;
            case 6:
                myLatlng = { 'lat': 43.66985832954972, 'lng': -79.3927001953125, 'zoom': 9 };
                break;
            case 7:
                myLatlng = { 'lat': 49.23732754665598, 'lng': -123.01116943359375, 'zoom': 10 };
                break;
            default:
                break;
        }
        self.lat = myLatlng.lat;
        self.long = myLatlng.lng;

        return myLatlng;

    }
	self.set_centerpoint = function (zone_id) {
        var options = self.get_centerpoint(zone_id);
        var myLatlng = new google.maps.LatLng(options.lat, options.lng);
        var myOptions = {
            zoom: options.zoom,
            center: myLatlng,
            mapTypeControlOptions: {
                mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE]
            },
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        $('.zone_coverage').show();
        $('#map_canvas').css('width', '670px');

        //reset center after resizing. (needed b/c issue with google maps)
        var c = map.getCenter();
        google.maps.event.trigger(map, 'resize');
        map.setCenter(c); 
        
    }
    self.get_locations = function () {
        $.post(self.marker_url, { latitude: self.lat, longitude: self.long, radius: 100 }, function (data) {
            self.locations = data;
            self.setMarkers();
        });
    }
    self.toggleLayers = function (id) {

        if (!id) {
            if (self.mapLayerToggle == 1) {
                for (i = 0; i < self.kmlLayer.length; i++)
                    self.kmlLayer[i].setMap(null);
                self.mapLayerToggle = 0;

            } else {
                for (i = 0; i < self.kmlLayer.length; i++)
                    self.kmlLayer[i].setMap(map);
                self.mapLayerToggle = 1;
            }
        }
        else {
            if (self.mapLayerToggle == 1) {
                if (id == 7) {
                    self.kmlLayer[0].setMap(null);
                    self.mapLayerToggle = 0;
                }

            } else {
                if (id == 7) {

                    self.kmlLayer[0].setMap(map);
                    self.mapLayerToggle = 1;
                }
            }
        }
    }
    self.setMarkers = function () {
        $.each(self.locations, function (i, locale) {
            var myLatLng = new google.maps.LatLng(locale.Lat, locale.Long);

            var bubble_content = locale.Address;

            bubble_content += (bubble_content.length > 0) ? "<br />" + locale.City : locale.City;
            bubble_content += "<br /><br /><a href='http://maps.google.com/maps?saddr=&daddr=" + locale.Address.replace(" ", "%20") + "%20" + locale.City.replace(" ", "%20") + "' target='_blank'>Get directions</a>"
            var marker = new google.maps.Marker({
                position: myLatLng,
                map: map,
                title: locale.Name,
                content: bubble_content,
                image: locale.Image,
                zIndex: i
            });
            map.addMarker(marker);
            //var j = i + 1;
            //console.log(map + " | " + i + ". " + marker.title + " | " + locale.lat + " | " + locale.lng);

            self.attachMessage(marker, i);
        });

        self.markers_visible = true;

    }
    self.toggleMarkers = function () {
        if (self.markers_visible) {
            for (i = 0; i < infoCase.length; i++) {
                infoCase[i].close();
            }
            map.clearMarkers();
            self.markers_visible = false;
        } else {
            self.setMarkers();
            self.markers_visible = true;
        }
    }
    self.attachMessage = function (marker, number) {
        var infowindowLevel = 0;
        var bubble_image = (marker.image != '') ? '<img src="' + self.img_base_url + marker.image + '" width="100" height="100" border="0" alt="' + marker.title + '" style="float:left;" />' : "";

        var contentString = '<div class="infoWindow" style="position: relative; width: 300px;">' +
		'<h2 style="font-family: arial; font-size: 14px; line-height: 15px; font-weight: bold; background:#F27428; padding: 5px 10px; color:#FFF; float:right; width: 265px; margin: 0 15px 5px 0;">' +
		marker.title +
		'</h2>' +
		bubble_image +
       	'<div class="infoDetails" style="color:#000; float:right; width: 160px; font-family: arial; padding: 7px 17px 0 0; line-height: 15px; font-size: 12px; z-index:1000;">' +
		marker.content +
		'</div>' +
		'</div>';
        var infowindow = new google.maps.InfoWindow({
            content: contentString,
            zIndex: number,
            name: number
        });
        infoCase[number] = infowindow;

        google.maps.event.addListener(marker, 'click', function () {
            //$("#map_canvas .infoWindow").parent().parent().parent().parent().each(function() { $(this).css("display","none") });
            for (i = 0; i < infoCase.length; i++) {
                infoCase[i].close();
            }
            //infowindow.close();
            infowindow.setZIndex(++infowindowLevel);
            infowindow.open(map, marker);
        });
    }


    self.init();
}

var setup_zone_map = new SetupZoneMap();

function SetupStoreMap() {
    var self = this;
    self.map_url = "/en/StoreLocator/AjaxFindStores";
    self.img_base_url = "/images/store-locator/marker-logos/";
    self.lat = null;
    self.long = null;
    self.radius = 10;
    self.locations = [];
    var infoCase = new Array();

    self.init = function () {
        if ($('#map_canvas').length > 0) {
            self.setup_map();
        }
    }

    self.setup_map = function () {
        google.maps.Map.prototype.markers = new Array();

        google.maps.Map.prototype.addMarker = function (marker) {
            this.markers[this.markers.length] = marker;
        };

        google.maps.Map.prototype.getMarkers = function () {
            return this.markers
        };

        google.maps.Map.prototype.clearMarkers = function () {
            for (var i = 0; i < this.markers.length; i++) {
                this.markers[i].setMap(null);
            }
            this.markers = [];
        };

        geocoder = new google.maps.Geocoder();

        var latlng = new google.maps.LatLng(49.2802359, -123.1254512);
        var myOptions = {
            zoom: 11,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);

        city_input = new InputWaterMark('#city_val', language.city_label_text);
        $('#city_search .btn-search').click(function (evt) {
            var where = jQuery.trim($('#city_val').val());
            if (where.length < 1)
                return false;
            self.codeAddress(where);
            return false;
        });
        $('#city_search').submit(function () {
            var where = jQuery.trim($('#city_val').val());
            if (where.length < 1)
                return false;
            self.codeAddress(where);
            return false;
        });


        postal_input = new InputWaterMark('#proximity', language.postalcode_label_text);
        $('#byproxy .btn-search').click(function (evt) {
            var where = jQuery.trim($('#proximity').val());
            self.radius = $('#byproxy select option:selected').attr('value');
            if (where.length < 1)
                return false;
            self.codeAddress(where);
            return false;
        });
        $('#byproxy').submit(function () {
            var where = jQuery.trim($('#proximity').val());
            self.radius = $('#byproxy select option:selected').attr('value');
            if (where.length < 1)
                return false;
            self.codeAddress(where);
            return false;
        });
    }


    self.codeAddress = function (where) {
        geocoder.geocode({ 'address': where, 'region': 'ca' }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                self.lat = results[0].geometry.location.lat();
                self.long = results[0].geometry.location.lng();
                map.setCenter(results[0].geometry.location);
                self.get_points();
            } else {
                //alert("Geocode was not successful for the following reason: " + status);
                alert("Sorry, there were no matches for your search");
            }
        });
    }

    self.get_points = function () {
        $.post(self.map_url, { latitude: self.lat, longitude: self.long, radius: self.radius }, function (json) {
            self.locations = json;
            self.setMarkers();
        });
    }    
    
    self.setMarkers = function () {
        map.clearMarkers();
        $.each(self.locations, function (i, locale) {
            var myLatLng = new google.maps.LatLng(locale.Lat, locale.Long);

            var bubble_content = locale.Address;

            bubble_content += (bubble_content.length > 0) ? "<br />" + locale.City : locale.City;
            bubble_content += "<br /><br /><a href='http://maps.google.com/maps?saddr=&daddr=" + locale.Address.replace(" ", "%20") + "%20" + locale.City.replace(" ", "%20") + "' target='_blank'>Get directions</a>"
            var marker = new google.maps.Marker({
                position: myLatLng,
                map: map,
                title: locale.Name,
                content: bubble_content,
                image: locale.Image,
                zIndex: i
            });
            map.addMarker(marker);

            self.attachMessage(marker, i);
        });
    }

    self.attachMessage = function (marker, number) {
        var infowindowLevel = 0;
        var bubble_image = (marker.image != '') ? '<img src="' + self.img_base_url + marker.image + '" width="100" height="100" border="0" alt="' + marker.title + '" style="float:left;" />' : "";

        var contentString = '<div class="infoWindow" style="position: relative; width: 300px;">' +
		'<h2 style="font-family: arial; font-size: 14px; line-height: 15px; font-weight: bold; background:#F27428; padding: 5px 10px; color:#FFF; float:right; width: 265px; margin: 0 15px 5px 0;">' +
		marker.title +
		'</h2>' +
		bubble_image +
       	'<div class="infoDetails" style="color:#000; float:right; width: 160px; font-family: arial; padding: 7px 17px 0 0; line-height: 15px; font-size: 12px; z-index:1000;">' +
		marker.content +
		'</div>' +
		'</div>';
        var infowindow = new google.maps.InfoWindow({
            content: contentString,
            zIndex: number,
            name: number
        });
        infoCase[number] = infowindow;

        google.maps.event.addListener(marker, 'click', function () {
            //$("#map_canvas .infoWindow").parent().parent().parent().parent().each(function() { $(this).css("display","none") });
            for (i = 0; i < infoCase.length; i++) {
                infoCase[i].close();
            }
            //infowindow.close();
            infowindow.setZIndex(++infowindowLevel);
            infowindow.open(map, marker);
        });
    }


    self.init();
}

var setup_store_map = new SetupStoreMap();

/* Setup Payment Page
********************************************************************************************/

function SetupPaymentPage() {
    var self = this;
    self.area_url = '/en/ajax/getservicearea';

    self.init = function () {
        $('.btn_proceed').unbind('click').click(function () {
            if ($(this).hasClass('disabled')) {
                return false;
            }
            $(this).parents('form').submit();
            return false;
        });

        $('.field-validation-error').parent('p').addClass('error');
        
        $('#Payment_LocaleProvince').change(function () {
            self.get_areas($(this).val(),$('#is_zone').val());
        });
        $('.billing_address').hide();

        if ($('input.billingaddress:checked').val() == 'other') {
            $('.billing_address').show();
        }
        $('input.billingaddress').click(function () {
            if ($('input.billingaddress:checked').val() == 'other') {
                $('.billing_address').show();
            } else {
                $('.billing_address').hide();
            }
        });

    }

    self.get_areas = function (prov,is_zone) {
        if (prov.length > 0) {
            $('#Payment_LocaleCity').html('<option value="">' + language.selectcity_label_text + '</option>');
            $.getJSON(self.area_url, { prov: prov, iszone: is_zone }, function (codes) {
                if (codes.length > 0) {
                    for (x = 0; x < codes.length; x++) {
                        $('#Payment_LocaleCity').append('<option value="' + codes[x].Value + '">' + codes[x].Text + '</option>');
                    }
                }
            });
        }
    }

    self.init();
}

var setup_payment_page = new SetupPaymentPage();


/* Setup Long Distance Dropdown on Plans Page
********************************************************************************************/

function LongDistanceDropdown(id,ddlType) {
    var self = this;
    self.url = '/' + language.language + '/ajax/GetLongDistanceRateCountries';
    self.urlFind = '/' + language.language + '/ajax/GetLongDistanceRate';
    self.ddlType = ddlType;
    self.id = id;

    self.init = function () {

        $(self.id).html('<option value="">' + language.selectcountry_label_text + '</option>');
        $('#code').html("");
        $('#rate').html("");
        if ($(self.id).length != 0)
            self.get_countries();
    }

    self.get_countries = function () {
        $.getJSON(self.url, { type: self.ddlType, lang : language.language }, function (codes) {
            if (codes.length > 0) {
                for (x = 0; x < codes.length; x++) {
                    $(id).append('<option value="' + codes[x].Value + '">' + codes[x].Text + '</option>');
                }
            }
        });

        $(self.id).change(function () {
            self.get_rates($(this).val());
        });
    }

    self.get_rates = function (prov) {
        if (prov.length > 0) {
            $.getJSON(self.urlFind, { type: self.ddlType, name: prov, lang: language.language }, function (codes) {
                if (codes.length > 0) {
                    for (x = 0; x < codes.length; x++) {
                        $('#code').html(codes[x].Code);
                        if (language.language == "fr")
                            $('#rate').html(codes[x].Rate + " $");
                        else
                            $('#rate').html("$" + codes[x].Rate);
                            
                    }
                }
            });
        }
    }

    self.init();
}
var longdistanceM = new LongDistanceDropdown(".monthly #longdistance_lookup", "monthly");
var longdistanceLTO = new LongDistanceDropdown(".limited_time_offers #longdistance_lookup", "monthly");
var longdistanceP = new LongDistanceDropdown(".prepaid #longdistance_lookup", "prepaid");
var longdistanceUT = new LongDistanceDropdown(".unlimited_talk #longdistance_lookup", "prepaid");



/* LOCATION SELECT PAGE
********************************************************************************************/
function SetupLocationPage(){
	var self = this;
	self.current_bubble_index = 0;
	self.english_bubble = 0;
	self.french_bubble = 1;
	self.timer = null;
	self.pause_animation = false;
	self.delay = 5000;
	self.timing = 200;
	
	self.init = function(){
		self.timer = setTimeout(function() { self.start_animation(); }, self.delay);
		$('#location .french a').mouseover(function(){
			if(!self.pause_animation){
				self.stop_animation()
				self.current_bubble_index = self.french_bubble;
				$('#feature .bubble img:eq('+self.english_bubble+')').css('top','43px');
				$('#feature .bubble img:eq('+self.english_bubble+')').hide();
				$('#feature .bubble img:eq('+self.french_bubble+')').css('top','0px');
				$('#feature .bubble img:eq('+self.french_bubble+')').show();
			}
			return false;
		});
		$('#location .french a').mouseout(function(){
			if(self.pause_animation){
				self.pause_animation = false;
				self.timer = setTimeout(function() { self.start_animation() }, self.delay);
			}
			return false;
		});
		$('#location .english a').mouseover(function(){
			if(!self.pause_animation){
				self.stop_animation()
				self.current_bubble_index = self.english_bubble;
				$('#feature .bubble img:eq('+self.french_bubble+')').css('top','43px');
				$('#feature .bubble img:eq('+self.french_bubble+')').hide();
				$('#feature .bubble img:eq('+self.english_bubble+')').css('top','0px');
				$('#feature .bubble img:eq('+self.english_bubble+')').show();
			}
			return false;
		});
		$('#location .english a').mouseout(function(){
			if(self.pause_animation){
				self.pause_animation = false;
				self.timer = setTimeout(function() { self.start_animation() }, self.delay);
			}
			return false;
		});
	}
	
	self.start_animation = function(){
		if(!self.pause_animation){
			$('#feature .bubble img:eq('+self.current_bubble_index+')').css('z-index',1);
			$('#feature .bubble img:eq('+self.current_bubble_index+')').animate({ top: '43px'}, self.timing, function(){
				var old_index = self.current_bubble_index;
				self.current_bubble_index = (self.current_bubble_index == 0) ? 1 : 0;
				$('#feature .bubble img:eq('+self.current_bubble_index+')').css('z-index',2);
				$('#feature .bubble img:eq('+self.current_bubble_index+')').css('top','43px');
				$('#feature .bubble img:eq('+self.current_bubble_index+')').show();
				$('#feature .bubble img:eq('+old_index+')').hide();
				$('#feature .bubble img:eq('+self.current_bubble_index+')').animate({ top: '0px'}, self.timing, function(){
					if(!self.pause_animation){
						self.timer = setTimeout(function() { self.start_animation() }, self.delay);
					}
				});
			});
		}
	}
	
	self.stop_animation = function(){
		self.pause_animation = true;
		clearTimeout(self.timer);
	}
	
	self.init();
}

function SetupLocationPage2(){
	var self = this;
	self.current_bubble_index = 0;
	self.english_bubble = 0;
	self.french_bubble = 1;
	self.timer = null;
	self.pause_animation = false;
	self.delay = 4000;
	self.timing = 200;
	
	self.init = function(){
		self.timer = setTimeout(function() { self.start_animation(); }, self.delay);
		$('#location .french a').mouseover(function(){
			if(!self.pause_animation){
				self.stop_animation()
				self.current_bubble_index = self.french_bubble;
				$('#feature .bubble img:eq('+self.english_bubble+')').hide();
				$('#feature .bubble img:eq('+self.french_bubble+')').show();
			}
			return false;
		});
		$('#location .french a').mouseout(function(){
			if(self.pause_animation){
				self.pause_animation = false;
				self.timer = setTimeout(function() { self.start_animation() }, self.delay);
			}
			return false;
		});
		$('#location .english a').mouseover(function(){
			if(!self.pause_animation){
				self.stop_animation()
				self.current_bubble_index = self.english_bubble;
				$('#feature .bubble img:eq('+self.french_bubble+')').hide();
				$('#feature .bubble img:eq('+self.english_bubble+')').show();
			}
			return false;
		});
		$('#location .english a').mouseout(function(){
			if(self.pause_animation){
				self.pause_animation = false;
				self.timer = setTimeout(function() { self.start_animation() }, self.delay);
			}
			return false;
		});
	}
	
	self.start_animation = function(){
		if(!self.pause_animation){
			$('#feature .bubble img:eq('+self.current_bubble_index+')').css('z-index',1);
			$('#feature .bubble img:eq('+self.current_bubble_index+')').fadeOut(self.timing, function(){
				var old_index = self.current_bubble_index;
				self.current_bubble_index = (self.current_bubble_index == 0) ? 1 : 0;
				$('#feature .bubble img:eq('+self.current_bubble_index+')').fadeIn(self.timing, function(){
					if(!self.pause_animation){
						self.timer = setTimeout(function() { self.start_animation() }, self.delay);
					}
				});
			});
		}
	}
	
	self.stop_animation = function(){
		self.pause_animation = true;
		clearTimeout(self.timer);
	}
	
	self.init();
}
if($('#location #feature').length > 0){ var setup_location_page = new SetupLocationPage2(); }


/* Other one-offs
********************************************************************************************/
$('#mod_myaccount').css('cursor', 'pointer').unbind('click').click(function () {
    url = $('#mod_myaccount_footer a').attr('href');
    window.open(url);
    return false;
});

/* Print on Confirmation 
********************************************************************************************/
$('.btn_print').unbind('click').click(function () {
    $(this).attr('href').replace('#', '');
    window.print(); 
    return false;
});


function setupTOC() {

    //remove these before start. 
    $('p.back_to_top').remove();
    //$('.support_nav').remove(); 

    //look for all articles h2's
    if ($('.article h2').length > 0) {
        var toc = "<ul>";

        $('.article h2').each(function () {
            var tmp_id = string_to_slug($(this).text()); //.replace(" ", "_").toLowerCase();
            $(this).attr('id', tmp_id);

            toc += "<li><a href='#" + tmp_id + "'>" + $(this).text() + "</a>";

            if ($(this).nextUntil('h2').length > 0) {
                if ($(this).children('.content_container').length == 0) {
                    $(this).nextUntil('h2').wrapAll("<div class='content_container line' />");
                }

                /*
                if ($(this).nextUntil('h2').find('h3').length > 0) {
                toc += "<ul>";
                $(this).nextUntil('h2').find('h3').each(function () {

                var tmp_id2 = $(this).text().replace(" ", "_").toLowerCase();
                $(this).attr('id', tmp_id2);
                toc += "<li><a href='#" + tmp_id2 + "'>" + $(this).text() + "</a></li>";
                if ($(this).children('.article').length == 0) {
                $(this).nextUntil('h3').wrapAll("<div class='content_container' />");
                }
                });
                toc += "</ul>";
                }
                */
            }
            toc += "</li>";
        });

        toc = toc + "</ul>";
        $('.content_container:last').removeClass('line');
        $('.support_nav').html(toc); //append before div class='article'
        $('.article').addClass('toc'); //add toc class so that it resizes.

    }

    /*
    $('div.content_container div.content_container').each(function(){
    if($(this).find('p.back_to_top').length == 0){
    $(this).append("<p class='back_to_top'><a href='#top'>^ Back to top.</a></p>");
    }
    });
    */

    $('div.content_container').each(function () {
        if ($(this).find('p.back_to_top').length == 0) {
            $(this).append("<p class='back_to_top'><a href='#top'>^ " + language.backtotop_label_text + "</a></p>");
        }
    });
}

function string_to_slug(str) {
    str = str.replace(/^\s+|\s+$/g, ''); // trim
    str = str.toLowerCase();

    // remove accents, swap ñ for n, etc
    var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
    var to = "aaaaeeeeiiiioooouuuunc------";
    for (var i = 0, l = from.length; i < l; i++) {
        str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
    }

    str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
    .replace(/\s+/g, '-') // collapse whitespace and replace by -
    .replace(/-+/g, '-'); // collapse dashes

    return str;
}
setupTOC();


/* Setup Toggle Content. 
********************************************************************************************/
function ToggleContent(obj_id) {
    var self = this;
    self.input_id = obj_id;

    self.init = function () {
        $(self.input_id).unbind('click').click(function () {
            $(self.input_id + '_content').toggle();
            return false;
        });
    }
    self.init();
}

var promoLegal = new ToggleContent('.legal_details');


/* Promotion Location Content
********************************************************************************************/

function PromotionLocations(obj_id) {
    var self = this;
    self.input_id = obj_id;
    self.init = function () {
        $(self.input_id).parent().next("div").hide();
        $(self.input_id + ':first').parent().next("div").show();
        $(self.input_id).unbind('click').click(function () {
            if ($(this).parent().next('div').is(':hidden')) {
                $(self.input_id).parent().next("div:visible").slideUp();
                $(this).parent().next('div').slideDown();
            }
            return false;
        });

    };

    self.init();
}

var promoLocations = new PromotionLocations('.locations');


/* Add a class to Promotion column
********************************************************************************************/

function FeaturedPlan() {
    var self = this;
   // self.promotion_value = "promotion";
    self.init = function () {
            if ($('#pick_your_plan').length > 0) {
            self.addFeaturedPlanClass();
        }
    }

    self.addFeaturedPlanClass = function () {
        if (location.hash) {
            var hashString = window.location.hash.slice(1);
             var featuredColumn = $('#' + hashString);
                //$('.' + hashString).addClass('highlighted');
             $(featuredColumn).addClass('highlighted');
           // }
        }
    }

    self.init();
}

var highlightedPlan = FeaturedPlan();

/* Google Analytics tracking 
*******************************************************************************************/
function SetupGoogleEventTracking() {
    self.init = function () {
        $('a').click(function () {
            var link = $(this);
            var href = link.attr("href");
            var rel = link.attr("rel");
            if (((href.match(/^http/i)) && (!href.match(document.domain))) || rel == "eventTrack") {
                if (typeof _gaq !== "undefined") {
                    self.addEventTracking(href);

                    if (link.attr('target') != '_blank') {
                        setTimeout('document.location = "' + href + '"', 100);
                        return false;
                    } else {
                        window.open(href);
                        return false;
                    }


                }
            }
        });

        $('#mod_myaccount').click(function () {
            var link = $(this);
            var href = link.attr("href");
            if (typeof _gaq !== "undefined") {
                self.addEventTracking(href);
            }
        });


    };


    self.addEventTracking = function (href) {
        var category = 'ExternalLink';
        var event = 'Click';
        var label = href;
        _gaq.push(['_trackEvent', category, event, label]);

    };

    self.init();

}
var externalLinkTracking = new SetupGoogleEventTracking();

/* PHONE PRICES - SET ACTIVE    
***************************************************************/
//function ActivePhonePricing_old() {
//    var self = this;

//    self.init = function () {
//        if ($('#phones.details').length > 0) {
//            $(".box_right input:radio").change(function () {
//                var radioBtn = this;
//                $(".price_point").removeClass("active");
//                //radio->td->tr->table->find(.price-point)
//                var priceTableTr = $(radioBtn).parent().parent();
//                var priceTableTd = priceTableTr.find(".price_point:has(.price)");

//                if (priceTableTd.length <= 0)
//                    priceTableTd = priceTableTr.parents("table").prevAll().find(".price_point:has(.price)").first();
//                priceTableTd.addClass("active");
//            });
//        }
//    }

//    self.init();

//}
//var t = new ActivePhonePricing_old();

//**************************TEST***************************************/
function ActivePhonePricing() {
    var self = this;

    self.init = function () {
        if ($('#phones.details').length > 0) {
            var selectedValue = $(".box_right input:radio:checked").val();
            var selectedPriceContainerID = 'agreement_' + selectedValue;
            var selectedPriceNoteID = 'pricenote_' + selectedValue;
            $('#' + selectedPriceContainerID).addClass("active");
            $('#' + selectedPriceNoteID).addClass("active");
            $(".box_right input:radio:checked").parent().next().addClass('highlighed')
            $(".box_right input:radio").change(function () {
                var radioBtn = this;
                selectedValue = $(".box_right input:radio:checked").val();
                selectedPriceContainerID = 'agreement_' + selectedValue;
                selectedPriceNoteID = 'pricenote_' + selectedValue;
                $(".price_display_container").removeClass("active");
                $(".price_note_container").removeClass("active"); 
                $('#phone_details .rounded_box .inner_box .box_right table td.highlighed').removeClass('highlighed');

                $('#' + selectedPriceContainerID).addClass("active");
                $('#' + selectedPriceNoteID).addClass("active");
                var radioBtnLbl = $(radioBtn).parent().next();

                radioBtnLbl.addClass('highlighed');
            });
        }
    }

    self.init();

}
var t = new ActivePhonePricing();
//IMEI SCRIPT - NEEDS TO BE ADDED TO THE SCRIPTS.JS FILE

function IMEILookup() {
    var self = this;

    self.init = function () {
        if ($('#imei_lookup').length > 0) {
            $('#imei_lookup .btn_go').unbind('click').click(function () {
                $('#imei_lookup').submit();
                return false;
            });

            $('#imei_lookup').submit(function () {
                $('#imei_lookup .success').remove();
                $('#imei_lookup .caution').remove();

                var imei_val = $('#imei_val').val();
                $.getJSON("https://www.virginmobile.ca/en/activation/check-imei.do?callback=?", { imei: imei_val }, function (data) {
                    if (data.errorMsg) {
                        if (language.language == "fr")
                            self.setup_message("caution", "Oh! Il y a un petit inconv&eacute;nient.", "<p>Il semblerait que votre t&eacute;l&eacute;phone actuel n&rsquo;est pas compatible avec nos cartes SIM. Ne vous inqui&eacute;tez pas &mdash; vous avez le choix parmi une gamme de <a href='/fr/phones'>t&eacute;l&eacute;phones Solo</a> formidables.</p>");
                        else
                            self.setup_message("caution", "Well, this is awkward.", "<p>It looks like your current phone isn&rsquo;t compatible. But don&rsquo;t worry &mdash; there are tons of great <a href='/en/phones'>Solo phones</a> to choose from.</p>");
                    } else {
                        if (language.language == "fr")
                            self.setup_message("success", "Fantastique! ", "<p>Il semblerait que votre t&eacute;l&eacute;phone " + data.manufacturer + " " + data.model + " fonctionnera sans probl&egrave;me. <a href='/fr/store-locator'>Visitez un de nos &eacute;tablissements</a> et nous entamerons ensemble votre migration.</p>");
                        else
                            self.setup_message("success", "Found it!", "<p>Your " + data.manufacturer + " " + data.model + " phone looks like it will work just fine. <a href='/en/store-locator'>Visit one of our locations</a> and let&rsquo;s get started!</p>");
                    }
                });

                return false;
            });
        }
    }
    self.setup_message = function (type, title, msg) {
        self.close();

        var box_top = parseInt($('.main_content_shell').offset().top) + (parseInt($('.main_content_shell').height()) / 2);
        var box_left = parseInt($('.main_content_shell').offset().left) + (parseInt($('.main_content_shell').width()) / 2);
        var msg_box = " \
<div class=\"msg_box\"> \
	<div class=\"msg_box_top\"></div> \
	<div class=\"msg_box_center\"> \
		<div class=\"msg_heading " + type + "\"> \
			" + title + " \
		</div> \
		<div class=\"msg_details\"> \
			" + msg + " \
		</div> \
	</div> \
	<div class=\"msg_box_bottom\"></div> \
	<div class=\"close_btn\"><a href=\"#\" >close</a></div> \
</div><!-- important_msg_container-->";
        $('body').append(msg_box);
        var height = parseInt($('.msg_box').height()) / 2;
        var width = parseInt($('.msg_box').width()) / 2;

        box_top -= height;
        box_left -= width;
        $('.msg_box').css('position', 'absolute').css('top', box_top + 'px').css('left', box_left + 'px');
        $('.msg_box').show();
        $('.msg_box .close_btn').unbind('click').click(function () {
            self.close();
            return false;
        });
    }
    self.close = function () {
        $('.msg_box').remove();
    }

    self.init();
}

var imeiLookup = new IMEILookup();

/* Inner Box Heights
********************************************************************************************/
function SetupIMEIBoxHeights() {
    var self = this;

    self.init = function () {
        if ($('#imei_lookup').length > 0) {
            $('.innerbox_container.left_box').parent().each(function () {
                if ($(this).find('.innerbox_container').length > 1) {
                    $(this).find('.innerbox_content_inner').css('height', 'auto');
                    var new_height = 0;
                    $(this).find('.innerbox_container').each(function () {
                        new_height = (parseInt($(this).find('.innerbox_content_inner').height()) > new_height) ? parseInt($(this).find('.innerbox_content_inner').height()) : new_height;
                    });
                    $(this).find('.innerbox_content_inner').css('height', new_height + "px");
                }
            });
        }
    }

    self.init();
}

var setup_imei_box_heights = new SetupIMEIBoxHeights();


/* Overlay Messages in Addon page
********************************************************************************************/
function SetupOverlay() {
    var self = this;
    self.current_obj = null;
    self.show_close = false;
    self.overlay_width = 393;
    self.added_class = "";

    self.init = function () {

    }
    self._setup_overlay = function (objRef) {
        self.close();
        self.current_obj = objRef;
        $(objRef).dialog({
            moveable: false,
            resizable: false,
            modal: true,
            width: self.overlay_width
        });
        $('.ui-dialog').css('position', 'absolute');
        $('.ui-dialog').css('overflow', 'visible');

        $('.ui-dialog-content').css('width', (self.overlay_width - 44) + 'px');
        if (self.added_class.length > 0) {
            $('.ui-dialog').attr('id', self.added_class);
            $('.ui-dialog-content').css('width', (self.overlay_width - 44) + 'px');
        }


        if (self.show_close) {
            $('.ui-dialog-titlebar-close').show();
        } else {
            $('.ui-dialog-titlebar').css('overflow', 'hidden');
        }
        var height = parseInt($('.ui-dialog').height());
        var window_height = parseInt($(window).height());
        var scrollTop = parseInt($(window).scrollTop());
        var top_position = (parseInt(window_height / 2) - parseInt(height / 2)) + scrollTop;
        var width = parseInt($('.ui-dialog').width());
        var window_width = parseInt($(window).width());
        var left_position = (parseInt(window_width / 2) - parseInt(width / 2));


        $('.ui-dialog').css('top', top_position + 'px');
        $('.ui-dialog').css('left', left_position + 'px');

        $('.ui-dialog .btn_cancel').click(function () {
            self.close();
            return false;
        });

        $('.ui-dialog .btn_confirm').click(function () {
            $('.btn_continue').parents('form').submit();
            self.close();
            return false;
        });
        $('.ui-dialog-titlebar-close').click(function () {
            self.close();
            return false;
        });

    }
    self.show = function (objRef, showClose) {
        if (showClose != null) {
            self.show_close = showClose;
        } else {
            self.show_close = false;
        }
        self.added_class = "";
        self.overlay_width = 393;
        self._setup_overlay(objRef);
    }
    self.show_sml = function (objRef, showClose) {
        if (showClose != null) {
            self.show_close = showClose;
        } else {
            self.show_close = false;
        }
        self.overlay_width = 290;
        self.added_class = 'sml_msg';
        self._setup_overlay(objRef);
    }
    self.show_lrg = function (objRef, showClose) {
        if (showClose != null) {
            self.show_close = showClose;
        } else {
            self.show_close = false;
        }
        self.added_class = "lrg_msg";
        self.overlay_width = 532;
        self._setup_overlay(objRef);
    }
    self.close = function () {
        if (self.current_obj != null) {
            $(self.current_obj).dialog('destroy');
            $('.ui-dialog').remove();
            $('.ui-widget-overlay').remove();
        }
    }

    self.init();
}

var setup_overlay = new SetupOverlay();


/*************************************************use overlay when clicked***************************/


/* Right Box Height: Adjust the height of the right box in the contact page
/* NOTE: Please place this at the very bottom of the script.js. (setTimeout is used)
********************************************************************************************/
function setRightBoxHeight() {
    var self = this;

    self.init = function () {
        if ($('#contact_us .chat_now a img').length > 0) {
            var right_table = $('#contact_us table#contactus_hours');
            var chatButton = $('.chat_now a img');
            var chatButtonHeight = chatButton.height();
            var leftColumnHeight = $('#contact_us .left').height();
            var rightColumnHeight = $('#contact_us .right').height();
            var rightTableBottomMargin = parseInt(right_table.css("margin-bottom"));
            var heightDifference = 0;
            var marginValue = 0;

            if (leftColumnHeight > rightColumnHeight) {  
                heightDifference = leftColumnHeight - rightColumnHeight;
                marginValue = rightTableBottomMargin + heightDifference;
                right_table.css("margin-bottom", marginValue + "px");
            }
            else if (leftColumnHeight < rightColumnHeight) { 
                heightDifference = rightColumnHeight - leftColumnHeight;
                marginValue = rightTableBottomMargin - heightDifference;
                right_table.css("margin-bottom", marginValue < 0 ? 0 : marginValue + "px");
            }
        }
    }
    self.init();
}

function delaySettingBoxHeight() {
    var set_rightBox_height = new setRightBoxHeight();
}

var t = setTimeout("delaySettingBoxHeight()", 1000);  // delay 1 second: (Wait until an image is fully loaded)



