﻿Tre = {};

/*	You need:
	1 A container element with the class "expandContainer" 
	2 An element to expand inside 1 with the class "expandable"
	3 A link with a parent with the class "expandLink" inside 1 wih onclick="Tre.Toggle(this);"

	Ex:
	<div class="expandContainer">
		<div class="expandable">Expandable</div>
		<p class="expandLink"><a href="javascript:" onclick="Tre.Toggle(this);"><img src="/media/images/expand-icon.png" alt="" /> Mer om ...</a></p>
	</div>
*/
Tre.Toggle = function(sender){
	//sender should be the expandContainer or an element inside of the expandContainer
	var container = ($(sender).hasClass('expandContainer') ?  $(sender) : $(sender).closest('.expandContainer'));
	
	if(container.find('.expandable').toggle().css('display') !== 'none'){
		_gaq.push(['_trackPageview', '/virtuell/expanderat/' + sender.text + '/' + location.href]);
		container.find('.expandLink a').each(function(){ $(this).attr('caption', $(this).html()).html('<img alt="" src="/media/images/contract-icon.png"> D&ouml;lj') });
	}
	else{
		container.find('.expandLink a').each(function(){ $(this).html($(this).attr('caption')) });
	}
	if(typeof(curvyCorners) !== 'undefined'){ curvyCorners.redraw(); }
	Tre.Lightbox.Position();
};

Tre.FetchMetadata = function (element) {
	return element.metadata({ type: 'attr', name: 'data' });
};

Tre.Lightbox = {
    Open: function (className, content) {
        _gaq.push(['_trackPageview', '/virtuell/lightbox/' + className + '/' + location.href]);
        $('body > form').prepend(
			'<div id="lightbox" class="' + className + '" onclick="if( !this.denyClose ){ Tre.Lightbox.Close(); } else { this.denyClose = 0; }">\
				<div class="lightBoxBlock block curvyIgnore" onclick="this.parentNode.denyClose=1;">\
					<div class="closeBtn"><a href="javascript:" onclick="Tre.Lightbox.Close();"><img src="/media/images/close-lightbox.png" alt="" /></a></div>'
					+ content +
				'</div>\
			</div>');
        Tre.Init('#lightbox');
        Tre.InitCurvyCorners();
    },
    Position: function () {
		if($('#lightbox').length == 0){
			return;
		}
        if ($('#lightbox').hasClass('compareChooseProduct') || $('#lightbox .lightBoxBlock').height() + 60 - $(window).height() < 0) {
			// we must use this method and not inline styles because of an IE 7-8 bug. If we set this with inline styles it cannot be overwritten for print.
			$('#lightbox').append('<style type="text/css" media="screen">#lightbox .lightBoxBlock { margin-top:-' + (($('#lightbox .lightBoxBlock').height() + 30) / 2) + 'px; margin-left:-' + (($('#lightbox .lightBoxBlock').width() + 30) / 2) + 'px;}</style>');
            //$('#lightbox .lightBoxBlock').css('marginTop', '-' + (($('#lightbox .lightBoxBlock').height() + 30) / 2) + 'px')
			//	.css('marginLeft', '-' + (($('#lightbox .lightBoxBlock').width() + 30) / 2) + 'px');
        }
		else {
			$('#lightbox').addClass('scrollable').height($(document).height());
			scroll(0, 0);
        }
    },

    Close: function () {
        $('#lightbox').remove();
    }
};

Tre.LightboxExistingData = {
	Open : function (content) {
		Tre.Lightbox.Open('existing_data', $(content).html());
	}
};

Tre.InfoLightbox = {
	Open : function(headline, content, imageSrc, className){
		Tre.Lightbox.Open( 'infoLightBox' + (className ? ' ' + className : ''), '<table><tr>' + (imageSrc ? '<td><img src="' + imageSrc + '" /></td>' : '') + '<td><h1>' + headline + '</h1></td></tr></table><div class="hr"></div><div class="text12">' + content  + '</div>');
	}
};
Tre.VideoLightbox = {
	Open : function(url){
		Tre.Lightbox.Open( 'videoLightbox', 
		'<object width="640" height="390">\
			<param name="movie" value="http://www.youtube.com/v/'+url+'?fs=1&amp;hl=en_GB">\
			</param><param name="allowFullScreen" value="true"></param>\
			<param name="allowscriptaccess" value="always"></param>\
			<embed src="http://www.youtube.com/v/'+url+'?fs=1&amp;hl=en_GB" \
			type="application/x-shockwave-flash" allowscriptaccess="always" \
			allowfullscreen="true" width="640" height="390"></embed>\
		</object>'
		);
	}
};

Tre.InterestNotificationLightbox = {
    Open: function (pageId, pageName, formProperty, type) {

        var formUrl = '/config/InterestFormGeneral.txt';
        if (type == 'MobileSwitch')
            formUrl = '/config/InterestFormMobileSwitch.txt';

        $.get(formUrl, function (data) {

            Tre.Lightbox.Open('mobileSwitchInterestNotificationLightbox', data);

            $("#contactInfo").hide();
            $('select[name=ContactMethod]:first').change(function () {
                if ($(this).val() != "-1") {
                    $("#contactInfoLabel").html(($(this).val() == "phone" ? "Telefon: <span>(inkl. riktnummer)</span>" : "E-post:"));
                    $("#contactInfo").show();

                }
            });

            $("#interestNotificationLightboxSubmit").click(function () {

                var mobileSwitch = $('select[name=MobileSwitch] option:selected').val();
                var customerName = $('input[name=CustomerName]:first').val();
                var city = $('input[name=City]:first').val();
                var contactMethod = $('select[name=ContactMethod] option:selected').val();
                var contactInfo = $('input[name=ContactInfo]:first').val();
                var coworkerCount = $('select[name=CoworkerCount]:first').val();
                var currentPhoneSolution = $('input[name=CurrentPhoneSolution]:first').val();
                var cid = $('input[name=CID]:first').val();
                var otherInformation = $('textarea[name=OtherInformation]:first').val();

                Tre.SendXForm("SubmitInterest",
			{
			    pageId: pageId,
			    formName: formProperty,
			    formData:
				{
				    pageName: pageName,
				    product: mobileSwitch,
				    customerName: customerName,
				    city: city,
				    contactMethod: contactMethod,
				    contactInfo: contactInfo,
				    coworkerCount: coworkerCount,
				    currentPhoneSolution: currentPhoneSolution,
				    cid: cid,
				    otherInformation: otherInformation
				}

			},
			function (data) {
			    var response = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;

			    if (response.Success) {
			        $.get("/Templates/UtilityPages/MobileSwitchInfoInterestMail.aspx",
	    		    {
	    		        pageId: pageId,
	    		        pageName: pageName,
	    		        mobileSwitch: mobileSwitch,
	    		        customerName: customerName,
	    		        city: city,
	    		        contactMethod: contactMethod,
	    		        contactInfo: contactInfo,
	    		        coworkerCount: coworkerCount,
	    		        currentPhoneSolution: currentPhoneSolution,
	    		        cid: cid,
	    		        otherInformation: otherInformation
	    		    });
			        Tre.Lightbox.Open('mobileSwitchInterestNotificationLightboxFeedback', '<p class="text12">' + response.Message + '</p> <div class="close"><a href="javascript:" onclick="Tre.Lightbox.Close();"><img src="/media/images/buttons/close-btn.png" alt="Stäng" /></a></div>');
			    }
			    else
			        Tre.Lightbox.Open('mobileSwitchInterestNotificationLightboxFeedback', '<p class="text12" style="color: #FF0000;">FEL: ' + response.Message + '</p> <div class="close"><a href="javascript:" onclick="Tre.Lightbox.Close();"><img src="/media/images/buttons/close-btn.png" alt="Stäng" /></a></div>');
			},
			function () {
			    Tre.Lightbox.Open('mobileSwitchInterestNotificationLightboxFeedback', '<p class="text12" style="color: #FF0000;">Ett fel uppstod när intresseanmälan skulle skickas.</p> <div class="close"><a href="javascript:" onclick="Tre.Lightbox.Close();"><img src="/media/images/buttons/close-btn.png" alt="Stäng" /></a></div>');
			});
                Tre.Lightbox.Close();

            });



        });
    }
};
   
Tre.IframeLightbox = {
	Open : function(url){
		Tre.Lightbox.Open( 'iframeLightBox', '<div class="iframeBlock"><div id="iframeWrapper">\
			<div id="ie6TopMenuCover"></div>\
			<iframe id="TreUtland" src="'
			+ url + 
			'" height="550" scrolling="yes" frameborder="0"></iframe></div></div>');		
	}
};
Tre.ConfirmLightbox = {
	Open : function(headline, content, callback){
		Tre.Lightbox.Open( 'confirmLightBox', '<h3>' + headline + '</h3><p class="text12">' + content  + '</p><div class="hr"></div><div class="buttonSpace"><div class="button"><a href="javascript:" onclick="Tre.Lightbox.Close();"><img src="/media/images/buttons/no-white-btn.png" alt="nej" /></a></div><div class="button confirmBtn"><a href="javascript:"><img src="/media/images/buttons/yes-btn.png" alt="ja" /></a></div></div>');
		$('#lightbox.confirmLightBox .confirmBtn').click(callback).click(function(){ Tre.Lightbox.Close(); });
	}
};
Tre.PromptLightbox = {
	Open : function(headline, content){
		Tre.Lightbox.Open( 'confirmLightBox', '<h3>' + headline + '</h3><p class="text12">' + content  + '</p><div class="hr"></div><div class="buttonSpace"><div><a href="javascript:" onclick="Tre.Lightbox.Close();"><img src="/media/images/buttons/close-btn.png" alt="Stäng" /></a></div></div>');
	}
};

Tre.My3Lightbox = {
	Open: function (aboutPageUrl) {
		var today = new Date()
		Tre.Lightbox.Open('my3Lightbox',
			'<div class="floatContainer tabs">\
				<div class="active"><a href="javascript:" onclick="Tre.My3Lightbox.TabOpen(\'login\',this);">Logga in</a></div>\
				<div><a href="javascript:" onclick="Tre.My3Lightbox.TabOpen(\'help\',this);">Hjälp med inloggning</a></div>\
				<div><a href="javascript:" onclick="Tre.My3Lightbox.TabOpen(\'register\',this);">Registrera dig</a></div>\
			</div>\
			<div class="tabLayers">\
				<div class="tabLayer" id="loginLayer">\
					<div class="body floatContainer" style="' + my3urls.showLogin + '">\
						<div class="imgContainer"><img src="/media/images/my3-lightbox-login.jpg" /></div>\
						<div class="txtContainer customForm">\
							<h3>Logga in</h3>\
							<input type="hidden" name="HiddenURI" value="' + my3urls.sesam3Url + '" />\
			                <input type="hidden" name="GARESOURCEID" value="' + my3urls.gareSourceId + '" />\
			                <input type="hidden" name="AUTHMETHOD" value="' + my3urls.authMethod + '" />\
			                <input type="hidden" name="pageGenTime" value="' + today.getUTCMilliseconds() + '" />\
			                <input type="hidden" name="LOCALE" value="sv_SE" />\
							<div class="floatContainer inputColumnContainer">\
								<div class="col">\
									<label for="Username">Mobilnummer&frasl;e-post:</label><br/>\
									<input type="text" id="loginUsername" tabindex="1" name="usr_name" class="my3login" />\
									<div class="forgotPasswordLnk"><a tabindex="4" onclick="Tre.My3Lightbox.DelayedClose();" href="' + my3urls.forgotPassword + '" target="_blank">Glömt lösenord?</a></div>\
								</div>\
								<div class="col">\
									<label for="Password">Lösenord:</label><br/>\
									<input type="password" id="loginPassword" tabindex="2" name="usr_password" class="my3login" />\
									<div class="logInBtn"><a tabindex="3" onclick="Tre.My3Lightbox.Login();" href="javascript:"><img src="/media/images/buttons/login-btn.png" alt="Logga in" /></a></div>\
								</div>\
							</div>\
						</div>\
					</div>\
					<div class="body floatContainer" style="font-size: 1.2em; ' + my3urls.showError + '">\
						<p>' + my3urls.errorMsg + '</p>\
					</div>\
					<div class="notice">Vad är det här? <a href="' + aboutPageUrl + '">Berätta mer om Mitt3</a></div>\
				</div>\
				<div class="tabLayer" id="helpLayer">\
					<h3>Du som har 1 abonnemang</h3>\
					<p>Du loggar in med ditt mobilnummer i formatet 0735XXXXXX eller 46735XXXXXX.</p>\
					<h3>Du som har 2 eller fler abonnemang</h3>\
					<p>Du måste registrera en administratör för att kunna se fakturor, ansöka om autogiro etc. Du får ett lösenord skickat till dig med post och loggar sedan in med den e-postadress du valde vid registreringen.</p>\
				</div>\
				<div class="tabLayer" id="registerLayer">\
					<div class="body floatContainer">\
						<div class="imgContainer"><img src="/media/images/my3-lightbox-register.jpg" /></div>\
						<div class="txtContainer">\
							<h3>Du som har 1 abonnemang</h3>\
							<p><a onclick="Tre.My3Lightbox.DelayedClose();" href="' + my3urls.newCustomerUrl + '" target="_blank">Klicka här för att registrera dig på Mitt3</a></p>\
							<h3>Du som har 2 eller fler abonnemang</h3>\
							<p>Du måste registrera en administratör för att kunna se fakturor, ansöka om autogiro etc.<br/><a onclick="Tre.My3Lightbox.DelayedClose();" href="' + my3urls.newAdministratorUrl + '" target="_blank">Registrera en administratör</a></p>\
						</div>\
					</div>\
				</div>\
			</div>');
		$("#my3Lightbox .customForm").jNice();

		$(".my3login").keydown(function (event) {
			if (event.which == 13) {
				Tre.My3Lightbox.Login();

				return false;
			}
		});
	},
	DelayedClose: function () {
		window.setTimeout("Tre.Lightbox.Close()", 1000);
	},
	TabOpen: function (name, sender) {
		$('#lightbox.my3Lightbox .tabLayers>div').hide().filter('#' + name + 'Layer').show();
		$('#lightbox.my3Lightbox .tabs>div').removeClass('active');
		$(sender.parentNode).addClass('active');
	},
	Login: function () {
		_gaq.push(['_setCustomVar', 1, 'Varit inloggad', 'Kund', 1]);
		var username = $("#loginUsername").val();

		if (username.indexOf("@") == -1 && username.charAt(0) == "0") {
			$("#loginUsername").val("46" + username.substring(1));
		}

		//set page generated time
		var today = new Date();
		var pageGenTime = today.getTime() - today.getMilliseconds();
		$("input[name='pageGenTime']").val(pageGenTime);

		//store original form values
		var formAction = document.forms[0].action;
		var formTarget = document.forms[0].target;
		var viewstate = $("input[name='__VIEWSTATE']").val();

		//empty viewstate value before submitting the form (oversized POST data issue) - by Nikolaj Carøe
		$("input[name='__VIEWSTATE']").val("");

		//set temporary form values
		document.forms[0].action = my3urls.authLoginUrl;
		document.forms[0].target = "_blank";
		document.forms[0].submit();

		//store original form values
		document.forms[0].action = formAction;
		document.forms[0].target = formTarget;
		$("input[name='__VIEWSTATE']").val(viewstate);

		Tre.My3Lightbox.DelayedClose();
	}
};

Tre.ReadMoreLightbox = {
    Open: function (type, id, customertype) {
		$.ajax({
            url: "/Templates/UtilityPages/ReadMoreLightbox.aspx",
            cache: false,
            data: "type=" + type + "&id=" + id + "&customertype=" + customertype,
            success: function(html) {
				Tre.Lightbox.Open('ReadMoreLightBox','<div>' + html + '</div>');					
            }
        });
	}
};

Tre.ReadMoreSubscriptionLightbox = {
    Open: function (id) {
        $.ajax({
            url: "/Templates/UtilityPages/ReadMoreSubscriptionLightbox.aspx",
            cache: false,
            data: "id=" + id ,
            success: function (html) {
                Tre.Lightbox.Open('ReadMoreSubscriptionLightBox', '<div>' + html + '</div>');
            }
        });
    }
};

Tre.CompareChooseProductLightbox = {
	Open : function(){
		$('#lightbox.compareChooseProduct').show();
		Tre.Init('#lightbox.compareChooseProduct');
		Tre.InitCurvyCorners();
	},
	
	Close : function() {
		$('#lightbox.compareChooseProduct').css('marginTop', '0px');
		$('#lightbox.compareChooseProduct').css('marginLeft', '0px');
		$('#lightbox.compareChooseProduct').hide();
	}
};

Tre.GetBalloon = function(forId) {
	return $('[for=' + forId + ']').filter('[generated=true]').parent();
};

Tre.ImageGallery = {
	/* arrayobject thumbs, arrrayobject full (full size images), string format (image format: "photo" or "product"), int limit */
    Populate: function(data, format, limit) {
        Tre.ImageGallery.Data = data;
        Tre.ImageGallery.Count = data.length;
		if(format){ Tre.ImageGallery.ImageFormat = format; }
		if(limit){ Tre.ImageGallery.Limit = limit; }
		// alt preload method. takes image tags, not urls
		for (var key in data){
			$('<div />').html(data[key]);
		}
    },
    Data: new Array(),
    Index: 0,
    Count: 0,
	Limit: 0,
	ImageFormat: null,
	ShowMore: function(){
		var elements = $('.imageGallery .image:hidden');
		for( var i = 0, n = Tre.ImageGallery.Limit; i < n; i++ ) {
			elements.eq(i).show();
		}
		if(!$('.imageGallery .image:hidden').length){
			$('.imageGallery .showMoreButton').hide();
		}
		if (typeof (curvyCorners) !== 'undefined') { curvyCorners.redraw(); }
	},
    Lightbox: {
        Open: function(index) {
            Tre.ImageGallery.Index = index;
            Tre.Lightbox.Open('ImageGalleryLightBox ' + (Tre.ImageGallery.ImageFormat || 'product'), '<div class="imgContainer">' + Tre.ImageGallery.Data[Tre.ImageGallery.Index] + '</div><p class="footer"><a href="javascript:Tre.ImageGallery.Lightbox.Prev();"><img src="/media/images/prev.png" /></a><span id="ImageGalleryImageNr">' + (Tre.ImageGallery.Index + 1) + '</span> av ' + Tre.ImageGallery.Count + '<a href="javascript:Tre.ImageGallery.Lightbox.Next();"><img src="/media/images/next.png" /></a></p>');
            $('.ImageGalleryLightBox .imgContainer').click(function(event) {
                if (event.pageX - $(this).offset().left < $(this).outerWidth() / 2) { Tre.ImageGallery.Lightbox.Prev(); }
                else { Tre.ImageGallery.Lightbox.Next(); }
            });
        },
        Next: function() {
            if (Tre.ImageGallery.Index + 1 >= Tre.ImageGallery.Count) { Tre.ImageGallery.Index = 0; }
            else { Tre.ImageGallery.Index++; }
            $('#ImageGalleryImageNr').text(Tre.ImageGallery.Index + 1);
            $('.ImageGalleryLightBox .imgContainer').html(Tre.ImageGallery.Data[Tre.ImageGallery.Index]);
        },
        Prev: function() {
            if (!Tre.ImageGallery.Index) { Tre.ImageGallery.Index = Tre.ImageGallery.Count - 1; }
            else { Tre.ImageGallery.Index--; }
            $('#ImageGalleryImageNr').text(Tre.ImageGallery.Index + 1);
            $('.ImageGalleryLightBox .imgContainer').html(Tre.ImageGallery.Data[Tre.ImageGallery.Index]);
        }
    }
};

Tre.Preload = function(images){
	var preimages = new Array();
	for (var key in images){
		preimages.push(new Image().src = images[key]);
	}
}

/*
Rules:
1. Tabs (labels) and nothing else needs to be in a .smartTabs container.
2. The layers connected to the tabs also needs to be in a container containing only them.
*/
Tre.Tabs = {};
Tre.Tabs.Show = function(id){
	$('.smartTabs label[for=' + id + ']').addClass('active').siblings().removeClass('active');
	$('#'+id).show().siblings().hide();
	if (typeof (curvyCorners) !== 'undefined') { curvyCorners.redraw(); }
}
Tre.Tabs.Scan = function(){
	$('.smartTabs label').click(function(){ Tre.Tabs.Show(this.htmlFor); });
	if(!$('.smartTabs label.active').length){
		$('.smartTabs label').first().addClass('active');
	}
}
// new smartTabs with a-links+anchors and live. 
$('.smartTabs a[href*=#]').live('click',function(e){ //should be ".smartTabs a[href^=#]" but ie7 doesn't like that
	e.preventDefault();
	$(this.hash).show().siblings().hide();
	if (typeof (curvyCorners) !== 'undefined') { curvyCorners.redraw(); }
});
// Because this function is dependant on the logic in the devicelists that sets the
// selected-class in the filter list and needs to be called after the specific lists init
// we need to call it from the lists script, not from Tre.Init()
Tre.SetFilterListMouseEffects = function() 
{
   	$("ul.filterList li.selected").css({ backgroundColor: "#00adef" });
   	$("ul.filterList li").hover(
		function() {
			if (!$(this).hasClass("selected"))
				$(this).stop().animate({ backgroundColor: "#cceffc" }, 200);
		},
		function() {
			if (!$(this).hasClass("selected"))
				$(this).stop().animate({ backgroundColor: "#ffffff" }, 500);
		}
	);
   	$("ul.filterList li").click(function() {
   		if ($(this).hasClass("selected"))
   			$(this).stop().animate({ backgroundColor: "#00adef" }, 500);
   		else
   			$(this).stop().animate({ backgroundColor: "#cceffc" }, 500);

   		$("ul.filterList li:not(ul.filterList li.selected)").not($(this)).stop().animate({ backgroundColor: "#fff" }, 500);
   	});
};

Tre.Init = function (context) {
	var siteInsideIframe = top.location != location;


	if (siteInsideIframe)
		$("#n38_160651").parent().remove();
	//fixing issues with floated elements with margin in IE7
	$('.ie7 .floatContainer > .block:not(.floatWrapped)', context).addClass('floatWrapped').wrap('<div class="floater" style="background:none !important; padding:0 !important; margin:0 !important;" />');

	// fix bug in curvycorners
	//$('.block > .floatContainer:not(.fcCCwrapper)').wrap('<div class="fcCCwrapper" />');

	// exclude curvycorners autoPadDiv or curvyCorners.redraw() will break
	//$('body *:not(script,.autoPadDiv):first-child', context).addClass('first');
	//$('body *:not(script,.autoPadDiv):last-child', context).addClass('last');
	$('tr:odd', 'table').addClass('even');
	$('tr:even', 'table').addClass('odd');
	//	$('.TinyMCE > *:last-child, .TinyMCE td > *:last-child').addClass('noMarginBottom');
	//img or p inside p for example.
	//	$('.noMarginBottom > *:last-child').addClass('noMarginBottom');
	$('.TinyMCE *:last-child').addClass('noMarginBottom');


	// removing text-to-image margins with css
	$('img[src*=class=price-tag]', context).addClass('priceTextImg');
	$('img[src*=class=price-tag-month]', context).removeClass('priceTextImg').addClass('textImg');

	// wrap tinyMCE-columns (we need it for margins in floated content)
	$('.TinyMCE .vansterkolumn:not(.colWrapped)', context).addClass('colWrapped').wrap('<div class="lColWrapper" />');
	$('.TinyMCE .hogerkolumn:not(.colWrapped)', context).addClass('colWrapped').wrap('<div class="rColWrapper" />');

	$("img.reflect").reflect({ height: 12 });
	$("img.reflect10light").reflect({ height: 10, opacity: 0.4 });
	$("img.reflect6light").reflect({ height: 6, opacity: 0.4 });
	Tre.SmallReflect();

	if (typeof ($.jNice) !== 'undefined') { $('.customForm', context).jNice(); }
	if (typeof ($.uniform) !== 'undefined') { $('.uniform', context).find('input:checkbox').uniform(); }

	if (siteInsideIframe) {
		// test if site is inside en iframe
		$(window).load(function () {
			//IE7 fix for disappearing fb likes
			setTimeout("Tre.InitCurvyCorners();$('.fblike').css('position', 'static');$('.fblike').css('position', 'relative');", 500);
		});
	}
	else {
		$(window).load(function () {
			Tre.InitCurvyCorners();
			//IE7 fix for disappearing fb likes
			$('.fblike').css('position', 'static');
			$('.fblike').css('position', 'relative');
		});
	}

	//removing outline in ie7
	$('a, button', '.ie7').focus(function () { this.blur(); });

	Tre.Tabs.Scan();
	// Add Google Analytics click events on file links
	$("a[href$='\\.pdf'], a[href$='\\.doc'], a[href$='\\.docx'], a[href$='\\.ppt'], a[href$='\\.pptx'], a[href$='\\.pps'], a[href$='\\.ppsx'], a[href$='\\.xls'], a[href$='\\.xslx'], a[href$='\\.zip'], a[href$='\\.exe'], a[href$='\\.vcf']").click(function (event) {
		var url = $(this).attr("href");
		var extension = url.substr((url.lastIndexOf('.') + 1));
		_gaq.push(['_trackPageview', '/virtuell/download/' + extension + '/' + url]);
	});

	// Add Google Analytics click events on external links
	$("a[href^='http']").click(function (event) {
		$(this).unbind();
		var url = $(this).attr("href");
		var domainName = window.location.hostname;
		if (url.indexOf(domainName) == -1) {
			url = url.replace("https://", "").replace("http://", "");
			_gaq.push(['_trackPageview', '/virtuell/external/' + url]);
		}
	});

	// Add Google Analytics focus events on form elements
	var runonceTracking = function () {
		if (typeof (FormTrackingRanOnce) == 'undefined') {
			_gaq.push(['_trackPageview', '/virtuell/formular/markerat-falt/' + location.href]);
		}
		FormTrackingRanOnce = 1;
	};
	$('input[type=text], input[type=radio], input[type=checkbox], select, textarea').not('.search, .searchpage, .csStartPageSearch').focus(runonceTracking).click(runonceTracking);

	// Add Google Analytics click on mailto-links
	$('a[href^=mailto:]').click(function () {
		var recipient = this.href.match(/mailto:(.*?)@/)[1];
		_gaq.push(['_trackPageview', '/virtuell/e-post/' + recipient + '/' + location.href]);
	});

}
Tre.SmallReflect = function(jqueryObj){
	if(jqueryObj)
		jqueryObj.reflect({ height: 4, opacity: 0.4 });
	else
		$("img.smallreflect").reflect({ height: 4, opacity: 0.4 });
}
Tre.InitCurvyCorners = function() {
	if (typeof (curvyCorners) !== 'undefined') {
		curvyCorners.init();
		curvyCorners.redraw();
		curvyCorners.scanStyles();
	}
	Tre.Lightbox.Position();
}

G = {
	Search : function (q) {
		location.href='http://www.google.se/search?q='+q;
	}
}

$(document).ready(function(){
	/*browser detect (customized and minified) */
	var a=navigator.userAgent.toLowerCase();$.browser.chrome=/chrome/.test(navigator.userAgent.toLowerCase());if($.browser.msie){$('body').addClass('ie');$('body').addClass('ie'+$.browser.version.substring(0,1))}if($.browser.chrome){$('body').addClass('browserChrome');a=a.substring(a.indexOf('chrome/')+7);a=a.substring(0,1);$('body').addClass('browserChrome'+a);$.browser.safari=false}if($.browser.safari){$('body').addClass('safari');a=a.substring(a.indexOf('version/')+8);a=a.substring(0,1);$('body').addClass('safari'+a)}if($.browser.mozilla){if(navigator.userAgent.toLowerCase().indexOf('firefox')!=-1){$('body').addClass('firefox');a=a.substring(a.indexOf('firefox/')+8);a=a.substring(0,1);$('body').addClass('firefox'+a)}else{$('body').addClass('mozilla')}}if($.browser.opera){$('body').addClass('opera')}

	//show campaignbanner if not closed this session
	if(!$.cookie('campaignBannerClosed')){
		$('.campaignBannerBlock').show();
	}
	
	Tre.Init(document);
	//preload images
	Tre.Preload(['/media/images/contract-icon.png', '/media/images/bagarrow.gif', '/media/images/lightbox-bg.png', '/media/images/balloon-body.png', '/media/images/color-hover.gif', '/media/images/color-active.gif']);
	Tre.ie6Notice();
});


Tre.ie6Notice = function(){
	$('body.ie6 form').prepend('<div id="ie6Container">\
		<div class="noticeBlockCS squareBlock">\
			<div class="floatContainer">\
				<div class="exclamation">\
					<img src="/media/images/exclamation.png" alt="tre" /></div>\
				<div class="body">\
					<h3>Viktig information: </h3>\
					<p>Du använder en gammal webbläsare som saknar stöd för funktionalitet på den här webbplatsen. <br />Du bör uppgradera till en senare version av t ex <a href="http://www.microsoft.com/windows/internet-explorer/default.aspx">Internet Explorer</a> eller <a href="http://www.mozilla-europe.org/sv/firefox/">Firefox</a>.</p>\
				</div>\
				<div class="download">\
					<a href="http://www.microsoft.com/windows/internet-explorer/default.aspx" onclick="$(this).closest(\'.noticeBlockCS\').hide();">\
						<img src="/media/images/download-explorer.png" alt="tre" /></a>\
				</div>\
				<div class="download">\
					<a href="http://www.mozilla-europe.org/sv/firefox/" onclick="$(this).closest(\'.noticeBlockCS\').hide();">\
						<img src="/media/images/download-firefox.png" alt="tre" /></a>\
				</div>\
			</div>\
		</div>\
	</div>');
}


Tre.SendXForm = function (remoteFunctionName, jsonData, successFunction, errorFunction) {
	$.ajax({
		type: "POST",
		url: "/WebServices/TreXFormWS.asmx/" + remoteFunctionName,
		contentType: "application/json",
		dataType: "json",
		data: $.toJSON(jsonData),
		success: typeof (successFunction) != 'function' ? function (data) { alert("Formuläret är skickat."); } : successFunction,
		error: typeof (errorFunction) != 'function' ? function () { alert("Formuläret kunde inte skickas."); } : errorFunction

	});
};

/**** To add tooltip to an element: use:

	$(<element>).tooltip({message: '<tool tip message>', id : <optional unique identifier>});
	
****/
$.fn.tooltip = function (options) {
	var id = options.id ? options.id : (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);

	var div = document.getElementById("toolTipContainer" + id);

	if (!div) {
		div = document.createElement("div");
		$(div).html(options.message);
		$(div).addClass("toolTipStyle");
		$(div).attr("id", "toolTipContainer" + id);
		$("body").append(div);
	}

	$(this).attr("toolTipId", id);

	this.each(function () {

		$(this).mousemove(function (e) {
			$("#toolTipContainer" + $(this).attr("toolTipId")).css({ 'top': e.pageY + 15, 'left': e.pageX + 15, 'display': 'block', 'visibility': 'visible' });
		});

		$(this).mouseout(function (e) {
			$("#toolTipContainer" + $(this).attr("toolTipId")).css({ 'display': 'none' });
		});

	});

	return this;
};

/* Deprecated stuff */


/* Still used, replace with smartTabs */
Product = {
    TabOpen: function(name, sender) {
		_gaq.push(['_trackPageview', '/virtuell/flikar/' + sender.text + '/' + location.href]);
		//wrapper for forward compability
		if(!$('.pTabContainer .pTab').length && $('.smartTabs label').length){
			Tre.Tabs.Show(name.toLowerCase());
			return;
		}
        $('#tabLayers>div.' + name).show().siblings().hide();
        $('.pTabContainer .pTab').removeClass('active');
        var index = $('#tabLayers>div').index($('div.' + name, "#tabLayers"));
        $(".pTabContainer .pTab").eq(index).addClass('active');
        if (typeof (curvyCorners) !== 'undefined') { curvyCorners.redraw(); }
    }
}


/* Deprecated! Used by previous datasubscription.js (modems) */
General = {
	Expand : function(id, object, contractText){
		$('#' + id + ' .expandLink a').attr('href','javascript:' + object + '.Contract();').html('<img alt="" src="/media/images/contract-icon.png"> ' + contractText + '</a>');
		$('#' + id + ' .expandable').show();
		if(typeof(curvyCorners) !== 'undefined'){ curvyCorners.redraw(); }
	},
	Contract : function(id, object, expandText){
		$('#' + id + ' .expandLink a').attr('href','javascript:' + object + '.Expand();').html('<img alt="" src="/media/images/expand-icon.png"> ' + expandText + '</a>');
		$('#' + id + ' .expandable').hide();
		if(typeof(curvyCorners) !== 'undefined'){ curvyCorners.redraw(); }
	}
};

/*

Tre.Expand = function(sender){
	// deprecated, now used as wrapper function for backward compability
	this.Toggle(sender);
};

Tre.Contract = function(sender){
	// deprecated, now used as wrapper function for backward compability
	this.Toggle(sender);
};
*/



/***** LIVE STORE ********/



var jsotemp;
LiveStore = {
	Url: null,
	Method: "POST",
	LsWindow: null,
	Show: function() { return $("#livestoreTop").show(); },
	SetWindow: function (win) {
		LiveStore.LsWindow = win;
	},
	UpdateStatus: function () {

		$.ajax({
			url: LiveStore.Url,
			data: { s: $.cookie(".SESSIONID") },
			type: LiveStore.Method,
			dataType: "json",
			success: function (jso, textStatus) {
				LiveStore.Show();
				var minLeft = Math.round(jso.time_left / 60.0);
				if (minLeft < 1)
					minLeft = 1;

				if (jso.pos > -1 && jso.pos < 2) {
					$("#livestoreTop").addClass("alert"); $("#livestoreTop img.alert").show(); $("#livestoreTop img.normal").hide();
					if (jso.pos == 0)
						$("#livestoreTop .caption").html("Nu är det din tur att besöka 3LiveShop.");
					else if (jso.pos == 1)
						$("#livestoreTop .caption").html("Nu är det snart din tur att besöka 3LiveShop: <strong>" + minLeft + " min</strong>");
				}
				else {
					$("#livestoreTop").removeClass("alert");
					if (jso.pos > -1) {
						$("#livestoreTop .caption").html("Din köplats: <strong>" + jso.pos + "</strong>&nbsp;&nbsp;&nbsp;Beräknad kötid: <strong>" + minLeft + " min<strong>");
					}
				}
				if (jso.poll_interval > 5) {
					setTimeout("LiveStore.UpdateStatus()", jso.poll_interval * 1000);
				}
			}
		});
	}
}


//TEST
$(function () {
	//$.cookie("LIVESTORE", "TEST123")
	//LiveStore.Url = "/Test/LiveStore/closed.js?";
	//LiveStore.Url = "/Test/LiveStore/finished.js?";
	//LiveStore.Url = "/Test/LiveStore/inqueue.js?";
	//LiveStore.Url = "/Test/LiveStore/manyinqueue.js?";
	//LiveStore.Url = "/Test/LiveStore/noneinqueue.js?";
	//LiveStore.Url = "/Test/LiveStore/pos1.js?";
	//LiveStore.Method = "GET";
});

$(function () {
	if ($.cookie(".SESSIONID") != null && LiveStore.Url != null) {
		$("#livestoreTop").addClass("active");
		LiveStore.UpdateStatus();
	}
	else
		LiveStore.Show();
});

//If we have an existing window, focus that and prevent opening
$(function () {
	$(".livestoreBtn a").click(function (evt) {
		if (LiveStore.LsWindow != null && !LiveStore.LsWindow.closed) {
			LiveStore.LsWindow.focus();
			evt.stopPropagation();
			return false;
		}
		else {
			window.open($(this).attr("href"), $(this).attr("target"), $(this).attr("data-openoptions"), true);
		}
	});
});

//General window open functionality
//$(function() {
//	$("a[data-openoptions]").live("click", function() {
//		window.open($(this).attr("href"), $(this).attr("target"), $(this).attr("data-openoptions"), true);
//		return false;
//	});
//});

/***** END LIVE STORE ********/
