$(document).ready(function() {
    Allstream.init_lang();
    Allstream.init_homepage();
    Allstream.init_nav();
    Allstream.init_secnav();
    Allstream.init_subnav();
    Allstream.init_sidebar();
	Allstream.init_webhosting_descriptions();
    Allstream.init_textbox_focus($('#availability-form input.text'), Allstream.postal_code_text);
    Allstream.init_textbox_focus($('#domain-check-form input.text'), Allstream.domain_name_text);

    Allstream.trim_intro_p();

    Allstream.Availability.init();

    Allstream.Subscribe.init();

    Allstream.WhitePaperSubscribe.init();

    Allstream.ShareSuccessStoryEmail.init();

    if ($('ul.tab-content')) {
        Allstream.list_to_tabs($('ul.tab-content'));
    }

    if ($('ul.blinds')) {
        Allstream.list_to_blinds($('ul.blinds'));
    }

    Allstream.init_homepage_userInfoFormTA();
    Allstream.init_video();
	
	Allstream.init_home_showcase();
        if (!document.location.href.match(/\/fr\//)) {
            Allstream.init_myownboss_feed();
        }
	Allstream.init_urgent_updates();
	
	Allstream.init_email_optin();
});

var Allstream = {
    email_text : 'enter email',
    postal_code_text : 'enter postal code',
    domain_name_text : 'yourname.com',
    lang_path : '',
	showcase_timer : 4000,
	showcase_count : 1,
	showcase_promo : 0,
	showcase_timeout_id : -1,
	mts_base_url : '',

    init_lang : function() {
        var url = document.location.pathname;
		
		if (document.location.hostname.match(/fjordlabs/))
			Allstream.mts_base_url = "http://mtsallstream.fjordlabs.com";
		else
			Allstream.mts_base_url = "http://mtsallstreamsmallbusiness.com";

        if (url.match(/\/fr\//)) {
            Allstream.lang_path = '/fr';

            Allstream.postal_code_text = 'Code postal';
            Allstream.email_text = 'Entrer l\'adresse de courriel';

            Allstream.Availability.no_postal_code = 'Veuillez entrer le code postal.';
            Allstream.Availability.invalid_postal_code = 'Impossible de trouver le code postal XXX XXX. Veuillez l\'entrer de nouveau.';
            Allstream.Availability.loading_msg = 'Vérification en cours...';
            Allstream.Availability.loading_img = '../img/loading.gif';

            Allstream.Subscribe.no_email = 'Veuillez entrer une adresse de courriel.';
            Allstream.Subscribe.invalid_email = 'Veuillez entrer une adresse de courriel valide.'
        }
    },

	init_homepage : function() {
		// Can not alter the header include so we have to change the wrapper
		// here using JS.
        if ($("#content.home").get(0)) 
		{
			$('#background-wrapper').css("padding-bottom", "29px");
			$('#background-wrapper').css("zoom", "1");
			$('#background-wrapper').css("border", "none");
			$('#background-wrapper').css("background-image", "url(" + Allstream.lang_path + "/img/home/bg.jpg)");
			$('#background-wrapper').css("background-repeat", "no-repeat");
			$('#background-wrapper').css("background-position", "center 0");
			$('#background-wrapper').css("background-color", "transparent");
//			$('#wrapper').css("margin-top", "26px");
//			$('#wrapper').css("padding-top", "10px");
			$('#wrapper').css("width", "988px");
			$('#wrapper').css("margin-top", "0px");
			$('#wrapper').css("padding-top", "0px");
			$('#wrapper').css("overflow", "visible");
                        $('#wrapper').css("background-image", "url(" + Allstream.lang_path + "/img/home/inner_bg.png)");
			$('#wrapper').css("background-repeat", "no-repeat");
			$('#wrapper').css("background-position", "0 15px");
			$('#wrapper').css("background-color", "transparent");
			$('#footer-wrapper').css({position: "relative", top: "-180px"});
//			$('#footer-wrapper').css("background-color", "transparent");
//			$('#footer').css("border-top", "2px solid #d9d9d6");

		}
	},
	
        init_video : function() {
            var swf_url = Allstream.lang_path + '/swf';
            var express_install = swf_url + '/expressInstall.swf';
            var hps = swf_url + '/hps_preloader.swf';
                    var flash_vars = { wmode: 'transparent' };

            if ($('#homepage-video').get(0)) {
                            $(".open-video").colorbox({width:"934", inline:true, href:"#inline-video", opacity:0.5,
                                    "onOpen":function(){
//                                            Allstream.video_lightbox_border ();
                                            // Track homepage video clicks.
                                            $.get("/tracking/watch-homepage-video.html", function(data){
                                            });
                                    }
                            });
    //            swfobject.embedSWF(swf_url + '/controls_914.swf', "homepage-video", "914", "345", "8.0.0", express_install, { vidpath : swf_url + '/homepage.flv' });
                swfobject.embedSWF(swf_url + '/video_player_914x340.swf', "homepage-video", "914", "345", "8.0.0", express_install, { vidpath : swf_url + '/Allstream_home1.flv' }, flash_vars);
            }
        },

        init_homepage_userInfoFormTA : function() {

            if ($('#homepage-userInfoFormTA').get(0)) {
                    $("#gallery-widget li, .sidebar-get-info-to-go").colorbox({width:"340", inline:true, scrolling: false, href:"#homepage-userInfoFormTA", opacity:0.5});
            }
        },

        init_home_showcase : function() {
            if ($('#gallery-widget').get(0)){
                gallery = $('#gallery-widget ul.gallery');

                if (gallery.length == 0) return;
                    var listingLength = gallery.children('li').length;
                    $('div#gallery-widget div.gallery-control span.gallery-status').text('1/' + listingLength.toString());

                    gallery.cycle({
                        fx: 'fade',
                        timeout: 5000,
                        speed: 600,
                        next: '#gallery-widget div.gallery-control a.gallery-forward',
                        prev: '#gallery-widget div.gallery-control a.gallery-back',
                        after: Allstream.onStoryTransition
                    });

                    if (listingLength == 1)
                    {
                            $('#gallery-widget div.gallery-control a.gallery-forward, #gallery-widget div.gallery-control a.gallery-back').click(function()
                            {
                                    return false;
                            });
                    }
                
            };
            
        },
        onStoryTransition: function(currSlideElement, nextSlideElement, options, forwardFlag){
            gallery = $('#gallery-widget ul.gallery');
            $('#gallery-widget div.gallery-control span.gallery-status').text((options.currSlide + 1).toString() + '/' + gallery.children('li').length.toString());
        },
	
	init_myownboss_feed : function() {
        if ($('ul.myownboss').get(0)) 
		{
			var parms = {};
			
			if ($('#content.home ul.myownboss').get(0)) 
				parms = { excerpt_length:120 };
			
			$.getJSON(
				"http://myownboss.ca/wp-content/themes/myownboss_new/feed-asb.php?callback=?",
				parms,
				function(data) {
					if (data.status == 0)
					{
//						jQuery("#serverError").html (data.error);
//						jQuery("#serverError").show ();
					}
					else
					{
						$("ul.myownboss p.article1").html('<span class="feed-title"><a href="' + data.link0 + '" target="_blank">' + data.name0 + '</a><br>'+ data.excerpt0 + '</span>');
						$("ul.myownboss p.article2").html('<span class="feed-title"><a href="' + data.link1 + '" target="_blank">' + data.name1 + '</a><br>'+ data.excerpt1 + '</span>');
						if ($('ul.myownboss p.article3').get(0))
						{
							$("ul.myownboss p.article3").html('<span class="feed-title"><a href="' + data.link2 + '" target="_blank">' + data.name2 + '</a><br>'+ data.excerpt2 + '</span>');
						}
						if ($('ul.myownboss p.article4').get(0))
						{
							$("ul.myownboss p.article4").html('<span class="feed-title"><a href="' + data.link3 + '" target="_blank">' + data.name3 + '</a><br>'+ data.excerpt3 + '</span>');
						}
						if ($('ul.myownboss p.article5').get(0))
						{
							$("ul.myownboss p.article5").html('<span class="feed-title"><a href="' + data.link4 + '" target="_blank">' + data.name4 + '</a><br>'+ data.excerpt4 + '</span>');
						}
					}
				}
			);
		}
	},

	init_urgent_updates : function() {
		$.getJSON(Allstream.mts_base_url + "/urgent-updates/get-urgent-updates.php?lang=" + 
			((Allstream.lang_path == "/fr")? "fr" : "en") + "&jsoncallback=?", 
		function(json){
			var ignoreMsgWithTimestamp = Allstream.Availability.get_cookie('urgent_updates_ts');
			
			if ((json.timestamp != "0") && (json.timestamp != ignoreMsgWithTimestamp))
			{
				$("#urgent-updates").html(
					'	<div id="updates-title"></div>' +
					'	<div id="updates-text">' + unescape(json.msg) + '</div>' +
					'	<div id="updates-close"><a href="#" onclick="Allstream.urgent_updates_close(' + json.timestamp + '); return false;"></a></div>'
				);
				$("#urgent-updates").slideToggle(600);
			}
		});
    },
	
	init_email_optin : function() {
		$(".open-email-popup").colorbox({width:"418", height:"300", inline:true, href:"#inline-email", opacity:0.5, scrolling:false,
//			"onOpen":Allstream.email_lightbox_border,
			"onLoad":function(){ $('#email-optin input[name=optin_type]').val('HOME') }
		});
		
		$(".open-email-adtile-popup").colorbox({width:"418", height:"300", inline:true, href:"#inline-email", opacity:0.5, scrolling:false,
//			"onOpen":Allstream.email_lightbox_border,
			"onLoad":function(){ $('#email-optin input[name=optin_type]').val('ADTILE') }
		});
		
		$(".open-email-footer-popup").colorbox({width:"418", height:"300", inline:true, href:"#inline-email", opacity:0.5, scrolling:false,
//			"onOpen":Allstream.email_lightbox_border,
			"onLoad":function(){ $('#email-optin input[name=optin_type]').val('FOOTER') }
		});
                
                if ($('#copy.enews').get(0)) {
                        $('#email-optin input[name=optin_type]').val('FOOTER');
                        $('#inline-email-container').appendTo('#copy').css({"display": "block", "width": "420px", "margin-left": "-40px","margin-top": "-20px"});
//                        $('#copy.enews #inline-email').css('padding', '0');
                }
		if (Allstream.Availability.get_cookie('email_optin') == "1")
			Allstream.enable_homepage_twitter();
	},
	
    init_nav : function() {
        var url_path = Allstream.get_url();
        url_path = url_path.substr(0, url_path.indexOf('/'));

        $('#header ul.nav li a').each(function() {
            var href = Allstream.get_href(this, true);
            if (href) {
                href = href.replace('/', '');
            }
            else {
                href = '';
            }
            if (href != "" && url_path == href) {
                $(this).addClass('active');
            }
        });
    },

    init_secnav : function() {
        var url_path = Allstream.get_url();

        url_path = url_path.substr(0, url_path.indexOf('/'));
        $('#header ul.sec-nav li a').each(function() {
            var href = Allstream.get_href(this);
            if (href) {
                href = href.replace('/', '');
            }
            else {
                href = '';
            }

            if (url_path == href && this.className != 'allstream-com') {
                $(this).addClass('active');
            }
        });
		
		$('ul.sec-nav li a.allstream-com,#footer ul.links li a.allstream-com').bind('click', function() {
		
			if ($('#allstream-com-popup').length == 0)
			{
				$('body').prepend (
					'<div id="allstream-com-popup">' +
					'	<a href="#" id="allstream-com-close-popup"></a>' +
					'	<div id="allstream-com-popup-text">' +
					'		<p>' + 
					((Allstream.lang_path == "/fr")? 
					'Si vous êtes propriétaire d’une entreprise comptant moins de 50 employés, vous êtes au bon endroit.</p><p>Les moyennes et les grandes entreprises trouveront pour leur part des services et des solutions en visitant le site ' :
					'If you\'re a business owner with fewer than 50 employees, you\'re in the right place.</p><p>If you are an Enterprise or mid-sized company, you can find services and solutions at '
					) +
					'<a href="http://www.allstream.com/">Allstream.com</a></p>' +
					'	</div>' +
					'</div>');
			}
				
			$('#allstream-com-popup').bind('click', function() {
				window.location.href = 'http://www.allstream.com' + Allstream.lang_path + '/home';
				return false;
			});
			
			$('#allstream-com-close-popup').bind('click', function() {
				$('#allstream-com-popup').hide ();
				return false;
			});
		
			$('#allstream-com-popup').center ();
			$(window).bind('resize', function() { $('#allstream-com-popup').center(); });
			$(window).bind('scroll', function() { $('#allstream-com-popup').center(); });
			$('#allstream-com-popup').show ();
			return false;
		});
		
    },

    init_subnav : function() {
        var url_path = Allstream.get_url();
        url_path = url_path.replace(/\/$/, '');

        var found = false;

        while (!found && url_path.indexOf('/') != -1) {
            $('#subnav li a').each(function() {
                var href = Allstream.get_href(this);
                if (href == url_path || href == url_path + '.html') {
                    $(this).addClass('active');

                    if ($(this).hasClass('has-children')) {
                        $(this)
                            .addClass('active-expanded')
                            .siblings('ul')
                                .show();
                    }
                    else {
                        $(this).parents('ul')
                            .show()
                            .siblings('a.has-children')
                                .addClass('expanded');
                    }

                    found = true;
                }
            });

            url_path = url_path.substr(0, url_path.length-1);
            url_path = url_path.substr(0, url_path.lastIndexOf('/'));
        }
    },
    
    init_sidebar: function(){
        if ($('.get-info-form').get(0)) {
                    $(".get-info-form").colorbox({width:"340", inline:true, scrolling: false, href:"#homepage-userInfoFormTA", opacity:0.5});
            }
    },
	
	init_webhosting_descriptions : function() {
	
		var i = 1;
		$('table.standard-table-4col-webhosting tbody td.description-col-off a').each(function() {
			$(this).bind('click', function() {
				var num = this.className.replace ("desc-btn-", "");
//				alert (num);
				var turn_current_off = false;
				
				$('table.standard-table-4col-webhosting tbody td.description-col-on a').each(function() {
					var num2 = this.className.replace ("desc-btn-", "");
					if (num2 != num)
					{
						$(this).parent().addClass('description-col-off');
						$(this).parent().removeClass('description-col-on');
//						$('table.standard-table-4col-webhosting tr#description-' + num2).slideToggle(200);
						$('table.standard-table-4col-webhosting tr#description-' + num2).hide();
					}
					else
						turn_current_off = true;
				});
				
//				$('table.standard-table-4col-webhosting tr#description-' + num).slideToggle(200);
				// Need to set the display for FF to display the proper widths instead of the toggle.
				if (!turn_current_off)
				{
					$('table.standard-table-4col-webhosting tr#description-' + num).show();
					$('table.standard-table-4col-webhosting tr#description-' + num).display = "";
				}
				else
				{
					$('table.standard-table-4col-webhosting tr#description-' + num).hide();
					$('table.standard-table-4col-webhosting tr#description-' + num).display = "none";
				}
				$(this).parents().toggleClass('description-col-off');
				$(this).parents().toggleClass('description-col-on');
				
				return false;
			});
			i++;
        });

	},

    init_textbox_focus : function(element, default_text) {
        element.val(default_text);
        element
            .focus(function() {
                if ($(this).val() == default_text) {
                    $(this).val('');
                }
            })
            .blur(function() {
                if ($(this).val() == '') {
                    $(this).val(default_text);
                }
            });
    },
	
	urgent_updates_close : function(timestamp) {
		$('#urgent-updates').slideToggle(200);
		// Store a cookie so we do not display this urgent update again.
		Allstream.set_urgent_updates_top_level_ts (timestamp);
	},

	get_urgent_updates_top_level_ts : function() {
		// Get timestamp cookie for the allstream site.  This will be called
		// by the mtsallstream site as it is in a frame and needs to update the
		// allstream cookie as well as it's own.
		return Allstream.Availability.get_cookie('urgent_updates_ts');
	},

	set_urgent_updates_top_level_ts : function(timestamp) {
		// Store a cookie so we do not display this urgent update again.
		Allstream.Availability.set_cookie('urgent_updates_ts', timestamp, 365);
	},
	
	enable_homepage_twitter : function() {
		if ($(".promo-right-container div.follow-us-twitter").get(0))
		{
			$(".promo-right-container div.enews").hide ();
			$(".promo-right-container div.follow-us-twitter").show ();
		}
	},

	video_lightbox_border : function() {
		$("#cboxContent").css("border","1px solid #fff");
	},
	
	email_lightbox_border : function() {
		$("#cboxContent").css("border","1px solid #dcdcdd");
	},
	
    list_to_tabs : function(list) {
        var tabs = $('<ul class="tabs no-bullets"></ul>');
        list.before(tabs);

        list.children('li').each(function(i) {
            //$(this).attr('id', '');

            var title = $(this).children('h2').html();
            var link = $(title);

            if (i == 0) {
                link.addClass('active');
            }

            var li = $('<li></li>');
            li.attr('class', $(this).attr('class'));

            link.click(function() {
                activate_tab($(this));
                return false;
            });

            li.append(link);
            tabs.append(li);

            $(this).children('h2').remove();
            if (i > 0) {
                $(this).hide();
            }
        });

        if (document.location.hash) {
            var class_name = $(document.location.hash).attr('class');
            $('ul.tabs li.tab').each(function() {
                if ($(this).attr('class') == class_name) {
                    activate_tab($(this).children('a'));
                    return false;
                }
            });
        }

        function activate_tab(link) {
            $('ul.tab-content li.tab').hide();
            $('ul.tabs li.tab a').removeClass('active');
            link.addClass('active');
            var href = link.attr('href');
            var hash = href.substr(href.indexOf('#'));
            $(hash).show();
            var offset = $("a[name='top']").offset();
            window.scrollTo(offset.left, offset.top);
        }
    },

    list_to_blinds : function(list) {
        list.find('li.blind div.content').hide();

        list.find('li.blind h3 a').click(function() {
            var was_open = false;

            if ($(this).parents('li.blind').hasClass('blind-active')) {
                was_open = true;
            }

            list.find('li.blind-active').removeClass('blind-active');
            list.find('li.blind div.content').slideUp(200);

            if (!was_open) {
                $(this).parents('li.blind').addClass('blind-active');
                $(this).parent().siblings('div.content').slideDown(200);
            }

            return false;
        });
    },

    trim_intro_p : function() {
      if ($('#copy *:first').get(0)) {
        if ($('#copy *:first').get(0).nodeName == 'P' || $('#copy *:first').get(0).nodeName == 'UL')
			$('#copy *:first').css('margin-top', '0');
      }
    },

    get_url : function() {
        var url = document.location.pathname;

        return url.replace(Allstream.lang_path + '/', '');
    },

    get_href : function(obj, level1) {
        var href = $(obj).attr('href');
        if (!href || href.indexOf('http://') == -1) {
            href = 'http://www.allstream.com' + Allstream.lang_path + '/' + href;
        }
        var url = parseUri(href);
        href = url['path'];
        href = href.replace(Allstream.lang_path + '/', '');
        if (level1)
            href = href.substr (0, href.indexOf('/'));
        href = href.replace(/\/$/, '');
        return href;
    }
};

Allstream.Availability = {
    no_postal_code : 'Please enter a postal code.',
    invalid_postal_code : 'Cannot find postal code: XXX XXX. Please re-enter.',
    loading_msg : 'Checking availability...',
    loading_img : 'img/loading.gif',

    init : function() {
        Allstream.Availability.base_url = Allstream.mts_base_url + Allstream.lang_path + '/smallbusiness';
        Allstream.Availability.check_url = Allstream.Availability.base_url + '/products-services/business-phone-internet/savings-calculator/check/';
        Allstream.Availability.availability_url = Allstream.Availability.base_url + '/products-services/business-phone-internet/savings-calculator/availability.js';

        // Remove sidebar 'availability if we've got the main form present
        if (document.location.href.match(/products-services\/phone-internet-service/)) {
            $('#sidebar .generic.availability, #sidebar .cfib').remove();
        }

        var code = Allstream.Availability.get_cookie('code');
        //var cache = Allstream.Availability.get_cookie('availability');
	var cache = false;
        // If we're in the Savings Calculator frameset
        if ($('#savings-calculator-frame').get(0) && code) {
            var new_url = Allstream.Availability.check_url + '?code=' + escape(code) + "&url=" + escape(window.location.pathname.substring(window.location.pathname.lastIndexOf("/")+1,window.location.pathname.lastIndexOf("."))) + "&random="+Math.round(Math.random()*2000) ;
            $('#savings-calculator-frame').attr('src', new_url);
        }

        if (cache) {
            $('#sidebar li.availability').html(cache).addClass('cached');
            Allstream.init_textbox_focus($('#email-optin input.text'), Allstream.email_text);
        }
        else {
            if ($('#sidebar li.availability').get(0) && code) {
                $('#sidebar li.availability').html(Allstream.Availability.get_loading_html());
                Allstream.Availability.add_js(Allstream.Availability.availability_url + '?code=' + escape(code)+ "&url="  + escape(window.location.pathname.substring(window.location.pathname.lastIndexOf("/")+1,window.location.pathname.lastIndexOf("."))) + "&random="+Math.round(Math.random()*2000));
            }
        }

        $('#availability-form').submit(function() {
            $('p.availability-form-error').hide();

            var code = $('#availability-form input[name=code]').val();
            if (code == Allstream.postal_code_text) {
                code = '';
            }

            var error_msg = '';
            if (!code) {
                error_msg = Allstream.Availability.no_postal_code;
            }
            else if (!Allstream.Availability.valid_postal_code(code)) {
                error_msg = Allstream.Availability.invalid_postal_code.replace('XXX XXX', code);
            }

            if (error_msg) {
                if (!$('p.availability-form-error').get(0)) {
                    $('#availability-form').before('<p class="error availability-form-error"></p>');
                }

                $('p.availability-form-error').hide().html(error_msg).fadeIn(500);

                return false;
            }

            Allstream.Availability.set_cookie('code', code, 365);
            Allstream.Availability.remove_cookie('availability');

            if ($('#sidebar li.availability').get(0)) {
                $('#sidebar li.availability').fadeOut(function() {
                    $(this).html(Allstream.Availability.get_loading_html()).fadeIn(function() {
                        Allstream.Availability.add_js(Allstream.Availability.availability_url + '?code=' + escape(code) + "&url="  + escape(window.location.pathname.substring(window.location.pathname.lastIndexOf("/")+1,window.location.pathname.lastIndexOf("."))) + "&random="+Math.round(Math.random()*2000));
                    });
                });
                return false;
            }
            else {
                return true;
            }
        });
    },

    get_loading_html : function() {
        return '<div class="loading"><img src="' + Allstream.Availability.loading_img + '" alt="Loading..." /> <p>' + Allstream.Availability.loading_msg + '</p></div>';
    },

    add_js : function(src) {
        var head = document.getElementsByTagName("head")[0];
        var script_tag = document.createElement('script');
        script_tag.type = 'text/javascript';
        script_tag.src = src;
        head.appendChild(script_tag);
    },

    set_cookie : function(name, val, days) {
        var date = new Date();
        date.setDate(date.getDate()+days);
        document.cookie = escape(name) + '=' + escape(val) + '; expires=' + date.toGMTString() + '; path=/';
    },

    get_cookie : function(name) {
        var cookies = document.cookie;

        if (cookies.length == 0) {
            return '';
        }

        var pos = cookies.indexOf(name + '=');
        if (pos == -1) {
            return '';
        }

        pos = pos + name.length + 1;
        pos_end = cookies.indexOf(';', pos);
        if (pos_end == -1) {
            pos_end = cookies.length;
        }

        return unescape(cookies.substring(pos, pos_end));
    },

    remove_cookie : function(name) {
        var date = new Date();
        date.setDate(date.getDate()-1);
        document.cookie = escape(name) + '=; expires=' + date.toGMTString() + '; path=/';
    },

    valid_postal_code : function(s) {
        s = s.replace(/[\s|-]/, '');

        if (s.length != 6)
            return false;

        if (s.match(/^([A-z][0-9]){3}$/) == null)
            return false;

        return true;
    }
};

Allstream.Subscribe = {
    no_email : 'Please enter an email address.',
    invalid_email : 'Please enter a valid email address.',

    init : function() {
        Allstream.init_textbox_focus($('#email-optin input.text'), Allstream.email_text);

        $('#email-optin').submit(function() {
            $('p.optin-form-error').hide();

            var email = $('#email-optin input[name=email]').val();
            if (email == Allstream.email_text) {
                email = '';
            }

            var error_msg = '';
            if (!email) {
                error_msg = Allstream.Subscribe.no_email;
            }
            else if (!Allstream.Subscribe.valid_email(email)) {
                error_msg = Allstream.Subscribe.invalid_email;
            }

			if (!error_msg)
			{
				$.getJSON(
					Allstream.mts_base_url + Allstream.lang_path + "/smallbusiness/products-services/subscribe/?callback=?",
					{ type: "email-optin", email: email, optin_type: $('#email-optin input[name=optin_type]').val() },
					function(data) {
						if (data.error != '')
						{
							error_msg = data.error;
						}
						else
						{
							$("#inline-email p").each (function(){ $(this).html (''); });
							$("#inline-email #email-optin").hide ();
							if (Allstream.lang_path != "/fr")
								$("#inline-email p.title").html ('Thank you! We will contact you soon with exclusive online content and special offers from Allstream Small Business.');
							else
								$("#inline-email p.title").html ('Merci! Nous communiquerons avec vous bientôt pour vous proposer du contenu en ligne exclusif et des offres spéciales d’Allstream Petites entreprises.');
							
							if ($(".promo-right-container div.enews").get(0)) 
							{
								Allstream.enable_homepage_twitter();
								Allstream.Availability.set_cookie ("email_optin", "1", 10*365);
							}
						}
					}
				);
			}
			
            if (error_msg) {
                if (!$('p.optin-form-error').get(0)) {
                    $('#email-optin').before('<p class="error optin-form-error"></p>');
                }

                $('p.optin-form-error').hide().html(error_msg).fadeIn(500);

                return false;
            }

            return false;
        });
    },

    // borrowed from http://docs.jquery.com/Plugins/Validation/Methods/email
    valid_email : function(s) {
        return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(s);
    }
};

Allstream.WhitePaperSubscribe = {
    init : function() {
        Allstream.init_textbox_focus($('#wpemail-optin input.text'), Allstream.email_text);

        $('#wpemail-optin').submit(function() {
            $('p.optin-form-error').hide();

            var email = $('#wpemail-optin input[name=email]').val();
            if (email == Allstream.email_text) {
                email = '';
            }

            var error_msg = '';
            if (!email) {
                error_msg = Allstream.Subscribe.no_email;
            }
            else if (!Allstream.Subscribe.valid_email(email)) {
                error_msg = Allstream.Subscribe.invalid_email;
            }

            if (error_msg) {
                if (!$('p.optin-form-error').get(0)) {
                    $('#wpemail-optin').before('<p class="error optin-form-error"></p>');
                }

                $('p.optin-form-error').hide().html(error_msg).fadeIn(500);

                return false;
            }

            Allstream.Availability.set_cookie ('s', $('#wpemail-optin input[name=s]').val(), 10*365);
            return true;
        });
    }
};

Allstream.ShareSuccessStoryEmail = {
    no_email : 'Please enter an email address.',
    invalid_email : 'Please enter a valid email address.',
    loading_msg : 'Submitting email...',
    loading_img : 'img/loading.gif',

    init : function() {
        Allstream.ShareSuccessStoryEmail.base_url = Allstream.mts_base_url + Allstream.lang_path + '/smallbusiness';
        Allstream.ShareSuccessStoryEmail.js_url = Allstream.ShareSuccessStoryEmail.base_url + '/success-stories/share-email/js-call/success-story-email.js';

        var email = Allstream.Availability.get_cookie('share_email');
        var cache = false;

        if ($('#sidebar li.success-story-email-list').get(0) && email) {
            Allstream.ShareSuccessStoryEmail.add_js(Allstream.ShareSuccessStoryEmail.js_url + '?email=' + escape(email)+ "&onload=1&url="  + escape(window.location.pathname.substring(window.location.pathname.lastIndexOf("/")+1,window.location.pathname.lastIndexOf("."))) + "&random="+Math.round(Math.random()*2000));
        }

        $('#success-story-email-optin').submit(function() {
            $('p.success-story-email-optin-error').hide();

            var email = $('#success-story-email-optin input[name=email]').val();
            if (email == Allstream.email_text) {
                email = '';
            }

            var error_msg = '';
            if (!email) {
                error_msg = Allstream.ShareSuccessStoryEmail.no_email;
            }
            else if (!Allstream.Subscribe.valid_email(email)) {
                error_msg = Allstream.ShareSuccessStoryEmail.invalid_email;
            }

            if (error_msg) {
                if (!$('p.optin-form-error').get(0)) {
                    $('#success-story-email-optin').before('<p class="error optin-form-error"></p>');
                }

                $('p.optin-form-error').hide().html(error_msg).fadeIn(500);

                return false;
            }

            Allstream.Availability.set_cookie('share_email', email, 365);

            if ($('#sidebar li.success-story-email-list').get(0)) {
                $('#sidebar li.success-story-email-list').fadeOut(function() {
                   $(this).html(Allstream.ShareSuccessStoryEmail.get_loading_html()).fadeIn(function() {
                        Allstream.ShareSuccessStoryEmail.add_js(Allstream.ShareSuccessStoryEmail.js_url + '?email=' + escape(email) + "&url="  + escape(window.location.pathname.substring(window.location.pathname.lastIndexOf("/")+1,window.location.pathname.lastIndexOf("."))) + "&random="+Math.round(Math.random()*2000));
                    });
                });
                return false;
            }
            else {
                return true;
            }
        });
    },

    get_loading_html : function() {
        return '<div class="loading"><img src="' + Allstream.ShareSuccessStoryEmail.loading_img + '" alt="Loading..." /> <p>' + Allstream.ShareSuccessStoryEmail.loading_msg + '</p></div>';
    },

    add_js : function(src) {
        var head = document.getElementsByTagName("head")[0];
        var script_tag = document.createElement('script');
        script_tag.type = 'text/javascript';
        script_tag.src = src;
        head.appendChild(script_tag);
    }
};

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.outerHeight() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.outerWidth() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

function toggle (name, noFoldCheck)
{
	var e;
	var callingWasOpen = false;
	
	if (!noFoldCheck)
	{
		if (name != 'calling_features')
		{
			e = document.getElementById ('calling_features_img');
			if (e && e.src.indexOf('down') != -1)
			{
				toggle ('calling_features', true);
				callingWasOpen = true;
			}
		}
		if (name != 'web_based_tools')
		{
			e = document.getElementById ('web_based_tools_img');
			if (e && e.src.indexOf('down') != -1)
				toggle ('web_based_tools', true);
		}
		if (callingWasOpen && (name == 'web_based_tools'))
		{
			window.scrollTo (0,200);
		}
	}
	
	var foldUp = false;
	
	e = document.getElementById (name+'_img');
	if (e)
	{
		if (e.src.indexOf('down') == -1)
			e.src = "img/subnav/arrow-down-orange.gif";
		else 
		{
			e.src = "img/subnav/arrow-right.gif";
			foldUp = true;
		}
	}
	
	e = document.getElementsByTagName('tr');
	for (var i = 0; i < e.length; i++) 
	{
		if (e[i].className.indexOf(name + '_off') != -1)
			e[i].className = e[i].className.replace(name+'_off',name+'_on');
		else if (e[i].className.indexOf(name + '_on') != -1)
			e[i].className = e[i].className.replace(name+'_on',name+'_off');

		if (foldUp)
		{
			if (e[i].className.indexOf('desc_on') != -1)
				e[i].className = e[i].className.replace('desc_on','desc_off');
		}
	}
	
	e = document.getElementsByTagName('img');
	for (var i = 0; i < e.length; i++) 
	{
		if (e[i].className == 'desc_img')
			e[i].src = "img/subnav/arrow-right.gif";
	}

	return false;
}

function toggle_desc (e, desc_name)
{
	// Get the passed in description element.
	var e2 = document.getElementById (desc_name);
	var eImg = false;
	
	// If the desc image is down/open then put it back up/closed and vice versa.
	for (var i = 0; i < e.childNodes.length; i++)
	{
		if (e.childNodes[i].tagName == 'IMG')
		{
			eImg = e.childNodes[i];
			if (e.childNodes[i].src.indexOf('down') == -1)
				e.childNodes[i].src = "img/subnav/arrow-down-orange.gif";
			else 
				e.childNodes[i].src = "img/subnav/arrow-right.gif";
		}
	}

	// Close all the description tr rows.
	els = document.getElementsByTagName('tr');
	for (var i = 0; i < els.length; i++) 
	{
		// Ignore the passed in element as it will be handled below.
		if (els[i] == e2)
			continue;
		if (els[i].className.indexOf('desc_on') != -1)
			els[i].className = els[i].className.replace('desc_on','desc_off');
	}

	// Close all the desc_imgs.
	els = document.getElementsByTagName('img');
	for (var i = 0; i < els.length; i++) 
	{
		if (els[i] == eImg)
			continue;
		if (els[i].className == 'desc_img')
		{
			if (els[i].src.indexOf('right') == -1)
				els[i].src = "img/subnav/arrow-right.gif";
		}
	}

	// Open or close this description row.
	if (e2)
	{
		if (e2.className.indexOf('desc_off') != -1)
			e2.className = e2.className.replace('desc_off','desc_on');
		else if (e2.className.indexOf('desc_on') != -1)
			e2.className = e2.className.replace('desc_on','desc_off');
	}

	return false;
}

function toggle_phone (e, desc_name)
{
	for (var i = 0; i < e.childNodes.length; i++)
	{
		if (e.childNodes[i].tagName == 'IMG')
		{
			if (e.childNodes[i].src.indexOf('down') == -1)
				e.childNodes[i].src = "img/subnav/arrow-down-orange.gif";
			else 
				e.childNodes[i].src = "img/subnav/arrow-right.gif";
		}
	}

	var e2 = document.getElementById (desc_name);
	if (e2)
	{
		if (e2.className.indexOf('phone_descr_off') != -1)
			e2.className = e2.className.replace('phone_descr_off','phone_descr_on');
		else if (e2.className.indexOf('phone_descr_on') != -1)
			e2.className = e2.className.replace('phone_descr_on','phone_descr_off');
	}

	return false;
}

var rnd_total = 2;
var hp_rnd_timer_amount = 7000;
/*
var hp_rnd = Math.floor(Math.random()*rnd_total);
var hp_rndImg = new Array(rnd_total);
var hp_rndImgOver = new Array(rnd_total);

function GetRandomHomePromoImg (doNotCallTimer)
{
	var rndHref = new Array(rnd_total);
	rndHref[0] = "#phone";
	hp_rndImg[0] = "img/home/phone-internet-promo.jpg";
	hp_rndImgOver[0] = "img/home/phone-internet-promo-hover.jpg";
	rndHref[1] = "#hps";
	hp_rndImg[1] = "img/home/hps-promo.jpg";
	hp_rndImgOver[1] = "img/home/hps-promo-hover.jpg";
//	rndHref[2] = "referral/";
//	hp_rndImg[2] = "img/home/referral-promo.jpg";
//	hp_rndImgOver[2] = "img/home/referral-promo-hover.jpg";
	
	if (!doNotCallTimer)
		hp_rnd = Math.floor(Math.random()*rnd_total);
	else
	{
		if (++hp_rnd >= rnd_total)
			hp_rnd = 0;
	}

	if (!doNotCallTimer)
		setTimeout ("TimerRandomHomePromoImg()", hp_rnd_timer_amount);
	
	var s = "";
	if (!doNotCallTimer)
		s = '<div id="homeRandomPromo">';
	s += '<a href="promotions/' + rndHref[hp_rnd] + '">' +
		'<img src="'+hp_rndImg[hp_rnd]+'" border="0" onmouseover="this.src=hp_rndImgOver[hp_rnd]" onmouseout="this.src=hp_rndImg[hp_rnd]" /></a>';
	if (!doNotCallTimer)
		s += '</div>';
	
	return s;
}

function TimerRandomHomePromoImg ()
{
	var s = GetRandomHomePromoImg (true);
	$('#homeRandomPromo').html (s);
//alert (s);
	setTimeout ("TimerRandomHomePromoImg()", hp_rnd_timer_amount);
}
*/
function WriteRandomPromoHeader ()
{
	var rndImg = new Array(2);
	var rndHref = new Array(2);
	rndHref[0] = "#phone";
	rndImg[0] = "promo-top";
	rndHref[1] = "#hps";
	rndImg[1] = "promo-top-2";
	
	document.write ('<div class="' + rndImg[0/*hp_rnd*/] + 
		'"><a href="promotions/' + rndHref[0/*hp_rnd*/] + '"></a></div>');
}

var sb_rnd = Math.floor(Math.random()*rnd_total);
var sb_rndImg = new Array(rnd_total);
var sb_rndImgOver = new Array(rnd_total);
	
function WriteRandomSidebarPromo (doNotCallTimer)
{
	var rndHref = new Array(rnd_total);
	rndHref[0] = "#phone";
	sb_rndImg[0] = "img/promo/phone-internet-promo-sb.jpg";
	sb_rndImgOver[0] = "img/promo/phone-internet-promo-sb-hover.jpg";
	rndHref[1] = "#hps";
	sb_rndImg[1] = "img/promo/hps-promo-sb.jpg";
	sb_rndImgOver[1] = "img/promo/hps-promo-sb-hover.jpg";
	rndHref[2] = "referral/";
	sb_rndImg[2] = "img/promo/referral-promo-sb.jpg";
	sb_rndImgOver[2] = "img/promo/referral-promo-sb-hover.jpg";

	if (!doNotCallTimer)
		sb_rnd = Math.floor(Math.random()*rnd_total);
	else
	{
		if (++sb_rnd >= rnd_total)
			sb_rnd = 0;
	}

	setTimeout ("WriteRandomSidebarPromo(1)", hp_rnd_timer_amount);
	
	var s = "";
	if (!doNotCallTimer)
		s = '<div id="sbRandomPromo">';
	s += '<a href="promotions/' + rndHref[sb_rnd] + '">' +
		'<img src="'+sb_rndImg[sb_rnd]+'" border="0" onmouseover="this.src=sb_rndImgOver[sb_rnd]" onmouseout="this.src=sb_rndImg[sb_rnd]" /></a>';
	if (!doNotCallTimer)
		s += '</div>';

	if (!doNotCallTimer)
		document.write (s);
	else
		$('#sbRandomPromo').html (s);
//	document.write ('<a href="promotions/' + rndHref[sb_rnd] + '">' +
//		'<img src="'+sb_rndImg[sb_rnd]+'" border="0" onmouseover="this.src=sb_rndImgOver[sb_rnd]" onmouseout="this.src=sb_rndImg[sb_rnd]" /></a>');
}

function IsEnglish ()
{
	return (document.location.pathname.match(/\/fr\//))? false : true;
}

function WhitePaperDocumentText (leftnav)
{
	var en = IsEnglish();
	var secret = getURLVar ('s');
	if (secret == '')
		secret = Allstream.Availability.get_cookie ('s');

	if (secret && (secret != ''))
	{
		if (!leftnav)
			Allstream.Availability.set_cookie ('s', secret, 10*365);

		var urlH = Allstream.mts_base_url + 
			((en)? '' : 'fr/') + 'smallbusiness/articles/white/paper/hosted-phone?s=' + secret;
		var url = Allstream.mts_base_url + '/getwhitepaper.php?lang=' + 
			((en)? 'en' : 'fr') + '&s=' + secret;
		
		if (!leftnav)
			document.write (
				'<a href="' + urlH + '">' + ((en)? 'READ MORE' : 'Plus de détails') + ':</a>' +
				'<a href="' + urlH + '" style="display: inline; font-weight: normal; padding-left: 10px;">' +
				((en)? 'Hosted Phone System Shopping Guide For Small Business' : 
					'Guide d’achat de systèmes téléphoniques hébergés à l’intention des petites enterprises') + 
				'</a>');
		else
			document.write (
				'<li><a target="_top" href="articles/white-paper.html">' +
				((en)? 'Hosted Phone System - White Paper' : 
					'Guide d’achat de systèmes téléphoniques hébergés à l’intention des petites enterprises') +
				'</a></li>');
//				'<li><a href="' + urlH + '">Hosted Phone System - White Paper</a></li>');
	}
	else if (!leftnav)
	{
		var s = "";
		var arr = new Array ();
		for (var i = 0; i < 26; i++)
			arr[arr.length] = String.fromCharCode(65+i);
		for (i = 0; i < 10; i++)
			arr[arr.length] = i;
		for (i = 0; i < 20; i++)
			s = s + arr[Math.floor(Math.random() * arr.length)];

		document.write (
			'<form id="wpemail-optin" method="post" action="' + Allstream.mts_base_url +
			((en)? '' : 'fr/') + 'smallbusiness/products-services/subscribe/">' +
			((en)? '>> Enter your email to subscribe for the guide:&nbsp;' : '>> Entrez votre adresse de courriel pour recevoir notre guide :&nbsp;') +
			'<input type="text" class="text" name="email" maxlength="255" />' +
			'<input type="hidden" name="type" value="white_paper" />' +
			'<input type="hidden" name="s" value="' + s + '" />' +
			'<input type="image" name="submit" src="' +
			((en)? 'img/blank.gif' : '../img/blank.gif') + 
			'" alt="Submit" class="button submit" />' +
			'</form>');
	}
}

function WhitePaperFrameUrl ()
{
	var secret = getURLVar ('s');
	if (secret == '')
		secret = Allstream.Availability.get_cookie ('s');

	var url = Allstream.mts_base_url + 
		((IsEnglish())? '' : 'fr/') + 'smallbusiness/articles/white/paper/hosted-phone?s=';
		
	if (secret && (secret != ''))
	{
		Allstream.Availability.set_cookie ('s', secret, 10*365);
		return url + secret;
	}
	else
		return url;

}

function getURLVar (urlVarName) 
{
	var urlHalves = String(document.location).split('?');
	var urlVarValue = '';
	if(urlHalves[1]){
		var urlVars = urlHalves[1].split('&');
		for(i=0; i<=(urlVars.length); i++){
			if(urlVars[i]){
				var urlVarPair = urlVars[i].split('=');
				if (urlVarPair[0] && urlVarPair[0] == urlVarName) {
					urlVarValue = urlVarPair[1];
				}
			}
		}
	}
	return urlVarValue;   
}

function charactersLeft (e, limit)
{
	var len = e.value.length;
	if (len >= limit) {
		e.value = e.value.substring(0, limit);
	}
//	$('#charLeft').text(limit - len);
}

