var homePageAlias = '/how-to-be-selfish';
var hasFlash = false;

function DoSWFObject()
{
    var minFlashVer = "9.0.0";
    if (swfobject.hasFlashPlayerVersion(minFlashVer))
    {
	    //var flashvars = { lang: lang, cmp: cmp, ctry: ctry, locale: locale };
	    var flashvars = { gaAccNum: "UA-8843120-2" };
	    var attributes = {};
	    var params = {};
	    params.play = "false";
	    params.loop = "false";
	    params.menu = "false";
	    params.quality = "high";
	    params.scale = "noscale";
	    params.salign = "tr";
	    params.seamlesstabbing = "true";
	    params.swliveconnect = "true";
	    params.allowfullscreen = "true";
	    params.allowscriptaccess = "always";
	    params.allownetworking = "all";
	    params.gaAccNum = "UA-8843120-2";

	    swfobject.embedSWF("/preloader.swf", "page", "100%", "100%", minFlashVer, "/resources/javascript/swfobject/expressInstall.swf", flashvars, params, attributes);
	}
	else
	{
	    ShowGetFlashMessage();
	}
}

function ShowGetFlashMessage()
{
    //Only show the message if they haven't seen it recently
    var cookieName = 'getFlash';
    var getFlash = $.cookie(cookieName);
    if (getFlash != '1')
    {
        //Show a message telling the user to get flash installed
        var getFlashHtml = '<a href="#" title="Close" class="modalCloseX simplemodal-close">x</a><div class="simplemodal-content"><h2>Adobe Flash Player required</h2><p>To fully enjoy the experience of the Radox website, you need to have Adobe Flash Player 9 or better installed.</p><p>Get the latest version of the Adobe Flash Player from <a href="http://www.adobe.com/flashplayer">www.adobe.com/flashplayer</a>.</p></div>';
        $(getFlashHtml).modal({
		    position: ["15%",],
		    close: false
	    });	
    	
    	//Set the cookie so they don't see the message again for a while
        $.cookie(cookieName, '1', { expires: 7 });
    }   
}

function CheckForFlash()
{    
	//If we have an object with an id of page, we know that SWFObject was successful
	var radoxApp = $('object#page');
	if (radoxApp.length > 0)
	{
	    //Add a class so that we can easily provide rules via css that only apply when we have flash support
		$('html').addClass('hasFlash');
		hasFlash = true;
		
		//We're using SWFFit so that users with smaller viewports can still see the whole flash movie by scrolling
		swffit.fit("page",980,640,null,null,true,false);
		
		//We're going to provide an initial anchor point for the flash app to do deep-linking
		var path = window.location.pathname;
		if (path == '/')
		{
		    //We're on the home page so if there is not already a hash we need to provide the home page path alias as the hash
		    if (window.location.hash.length == 0)
		    {
		        window.location.hash = homePageAlias;
		    }
		}
		else
		{
		    window.location = '/#' + path;
		}
	}
}

function InitShareThis()
{
    var shareThisLink = $('<p id="sharePage"><a href="#sharePage"><img src="/resources/images/icons/share.gif" alt="Share this page" title="Share this page" /> Share this page</a></p>');
    shareThisLink.find('a').click(function(){
        return LaunchShareThis();
    });
    $('div#footer').prepend(shareThisLink);
}

function LaunchShareThis()
{
    var url = window.location.href;
    if (hasFlash)
    {
        var host = window.location.host;
        var hash = window.location.hash;
        
        //SWFAddress is placing a trailing slash in at the end of the hash that we don't want
        if (hash.endsWith('/'))
        {
            hash = hash.substring(0, hash.length - 1);
        }

        //Remove the hash from the url and also if we're on the home page we need to remove the hash completely
        var url = hash.replace('#/', '/');
        url = url.replace(homePageAlias, '/');
        url = 'http://' + host + url;
    }
    
    var title = document.title;
    
    //Create the AddThis URL and launch the popup window
    try
    {
        var u = "http://www.addthis.com/bookmark.php?v=250&url="+encodeURIComponent(url)+"&title="+encodeURIComponent(title);
        var n = "addthisPopup";
        var vars = "width=330,height=381";
        var w = window.open(u, n, vars);
        if (w.focus)
        {
            w.focus();
        }
    }
    catch(e)
    {
        if (console && console.log)
        {
            console.log(e);
        }
        throw e;
    }
    
    return false;
}

//ExternalLinks - tracking based on http://www.iqcontent.com/blog/2007/02/tracking-documents-and-external-links-in-google-analytics/
(function($) {
    $.fn.extend({
        ExternalLinks : function() {            
            return this.each(function() {
                $(this).click(function() {                    
                    if (this.tagName != 'A') {
                        return false;
                    }
                    
                    var link = String(this);
                    var linkHost = this.hostname;
                    var siteHost = location.host;
                    
		            if (link.match(/^mailto:/i)) 
		            {
		                return HandleMailToLink(this);
		            }
		            else if (linkHost == siteHost) 
		            {
			            if(link.match(/\.(doc|pdf|xls|ppt|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)$/)) 
			            {
		                    return HandleDocumentLink(this);
			            }
			            else
			            {
		                    return HandleInternalLink(this);
			            }
		            }
		            else 
		            {
		                return HandleExternalLink(this);
		            }
                });
            });
        
            function HandleMailToLink(anchor)
            {
                var email = anchor.href.substring(7);
                //TrackLink('mailto', email);
                
                return true;
            }
            
            function HandleDocumentLink(anchor)
            {
                var doc = CleanURL(anchor.pathname, false);
                //TrackLink('download', doc);                
                
                window.open(anchor.href);		            
                return false;
            }
            
            function HandleInternalLink(anchor)
            {                
                window.open(anchor.href);		            
                return false;
            }
            
            function HandleExternalLink(anchor)
            {
                var link = CleanURL(anchor.hostname+'/'+anchor.pathname, true);
                //TrackLink('external', link);
                
                window.open(anchor.href);		            
                return false;
            }
            
            function TrackLink(type, virtualPath)
            {
                if (typeof(pageTracker) != 'undefined')
                {
	                var url = CleanURL(window.location.pathname, true);
	                if (url.length == 0)
	                {
	                    url = '/home';
	                }
	                var linkStr = CleanURL('/virtual/'+type+url+'/'+virtualPath, true);
	                pageTracker._trackPageview(linkStr);
	            }
            }
            
            function CleanURL(url, end)
            {
	            var url = url.toString();
	            var urlLen = url.length;
            	
	            if (end)
	            {
		            if (url.charAt((urlLen-1))=='/') {
			            url = url.substring(0,(urlLen-1));
			        }
	            }
	            else
	            {
		            if (url.charAt(0)=='/') {
			            url = url.substring(1,urlLen);
			        }
	            }
	            return url;
            }
        }
    });
})(jQuery);

String.prototype.endsWith = function(t, i)
{
    if (i == false)
    {
        return (t == this.substring(this.length - t.length));
    }
    else
    {
        return (t.toLowerCase() == this.substring(this.length - t.length).toLowerCase());
    }
} 

$.clientCoords = function()
{
     var dimensions = { width: 0, height: 0 };
     if (document.documentElement)
     {
         dimensions.width = document.documentElement.offsetWidth;
         dimensions.height = document.documentElement.offsetHeight;
     }
     else if (window.innerWidth && window.innerHeight)
     {
         dimensions.width = window.innerWidth;
         dimensions.height = window.innerHeight;
     }
     return dimensions;
}

$(document).ready(function(){
    DoSWFObject();
    InitShareThis();
    $('a[rel="external"]').ExternalLinks();
});

$(window).load(function(){
    CheckForFlash();
});
