﻿var timeout = 500;
var closetimer = 0;
var ddmenuitem = 0;
var closetab;
var bodyWidth = 0;
var modalWidth = 0, modalHeight = 0;
var bannerRotateInterval;

function jsddm_open() {
    jsddm_canceltimer();
    jsddm_close();
    closetab = $(this).addClass("hover");
    ddmenuitem = $(this).find('ul').css('visibility', 'visible'); //$(this).find('ul').css('visibility', 'visible');
}

function jsddm_close() {
    if (ddmenuitem) {
        ddmenuitem.css('visibility', 'hidden');
        closetab.removeClass('hover');              
    }
}

function jsddm_timer() {   
    closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer() {
    if (closetimer) {
        window.clearTimeout(closetimer);
        closetimer = null;
    } 
}

function showDSSelection()
{
    $('.ds-item').hide();

    var val = $('#ds-category').val();
    
    if (val == "all")
    {
        $('.ds-item').show();        
    }
    else    
    {
        $("#" + val).show();        
    }
}

function ClearSalesMenu() {
	$(".sales-menu div").each(function() {
		$(this).removeClass();
	});
	
	$("#contactbottom span").each(function() {
		$(this).css("display", "none");
	});
	
	$("#contactbottom-left span").each(function() {
	    $(this).css("display", "none");
	});
}

// All right-column hover images with on and off states
function ImageHover(name, ext, state) {    
    if (state == "on")
        $("#" + name).attr("src", ("/images/right-column/" + name + "_on." + ext));
    else
        $("#" + name).attr("src", ("/images/right-column/" + name + "_off." + ext));
}

// Generic image swap function for roll-overs anywhere on the site
function swapImage(idName, imgPath) {
    $("#" + idName).attr("src", imgPath);
}

function homeImageHover(name, ext, state) {
    if (state == "on")
        $("#" + name).attr("src", ("/images/homepage/" + name + "_on." + ext));
    else
        $("#" + name).attr("src", ("/images/homepage/" + name + "_off." + ext));
}

function openWin(path) {
    window.open(path, "softlayer", "width=900,height=600");
}

function adjustModal() {
	var style = "width: " + modalWidth + "px; height: " + modalHeight + "px; display: block;";
	$('#modal').attr('style', (style + " left: " + returnLeftAlignment(modalWidth) + "px;"));
}

function openModal(path, width, height) {
	if (width == null) width = 900;	
	if (height == null) height = 600;

	var style = "width: " + width + "px; height: " + height + "px;";
		
	var containerId = document.getElementById("modal");	
	containerId.setAttribute('style', (style + " left: " + returnLeftAlignment(width) + "px;"));

	var modalContent = document.getElementById("modal-content");
	containerId.appendChild(modalContent);
	modalContent.setAttribute('style', style);
	
	modalContent.innerHTML = "";	// remove any HTML in the modal div.
	
	var ifrm = document.createElement("iframe");
	ifrm.setAttribute("src", path);
	ifrm.setAttribute("frameBorder", "0");
	ifrm.setAttribute('border', '0');
	ifrm.setAttribute('width', width + "px");
	ifrm.setAttribute('height', height + "px");
	
	modalContent.appendChild(ifrm);	
	
	$("#modal").jqmShow();
	
	// set global width values for possible adjustment on resize.
	bodyWidth = $("body").css("width");
	modalWidth = width;
	modalHeight = height;
}

function returnLeftAlignment(modalWidth) {
	return Math.round(($('body').width() / 2) - (modalWidth / 2));
}


function imageSwap(id, imageUrl) {
	$('#configuration').attr('src', imageUrl);

	$('h2 span a').each(function() {
		$(this).removeClass('active');
	});

	$('#' + id).addClass('active');
}

function toCurrentNetworkMap()
{
    //alert ($('#current-network-map').html());
    $('#network-map-title').html($('#current-network-title').html());
    $('#network-map-content').html($('#current-network-map').html());
}

function toFutureNetworkMap()
{
    $('#network-map-title').html($('#new-network-title').html());
    $('#network-map-content').html($('#new-network-map').html());
}

//SWF Detect from Adobe -----------------------

var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;
	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry
	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}
	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful.

			// default to the first public version
			version = "WIN 6,0,21,0";
			// throws if AllowScripAccess does not exist (introduced in 6.0r47)
			axo.AllowScriptAccess = "always";
			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}

	return version;
}

   function GetSwfVer(){
    // NS/Opera version >= 3 check for Flash plugin in plugin array
    var flashVer = -1;

    if (navigator.plugins != null && navigator.plugins.length > 0) {
        if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
            var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
            var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
            var descArray = flashDescription.split(" ");
            var tempArrayMajor = descArray[2].split(".");
            var versionMajor = tempArrayMajor[0];
            var versionMinor = tempArrayMajor[1];
            var versionRevision = descArray[3];
            if (versionRevision == "") {
                versionRevision = descArray[4];
            }
            if (versionRevision[0] == "d") {
                versionRevision = versionRevision.substring(1);
            } else if (versionRevision[0] == "r") {
                versionRevision = versionRevision.substring(1);
                if (versionRevision.indexOf("d") > 0) {
                    versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
                }
            }
            var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
        }
    }
    // MSN/WebTV 2.6 supports Flash 4
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
    // WebTV 2.5 supports Flash 3
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
    // older WebTV supports Flash 2
    else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
    else if ( isIE && isWin && !isOpera ) {
        flashVer = ControlVersion();
    }
    return flashVer;
}

function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];
        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

$(function() {
	bodyWidth = $('body').width();
		   
	// DropDown Menus
	$('#jsddm > li').bind('mouseover', jsddm_open)
	$('#jsddm > li').bind('mouseout', jsddm_timer)

	$("#phone-content").show();

	$(".sales-menu #chat").mouseover(function() {
		ClearSalesMenu();

		$("#specials").addClass("specials-inactive");
		$("#chat").addClass("chat-active");
		$("#email").addClass("email-inactive");
		$("#phone").addClass("phone-inactive");

		$("#contactbottom #chat-content").css("display", "block"); //remove after unify sprites for sub pages
		$("#contactbottom-left #chat-content").css("display", "block");
	});

	$(".sales-menu #email").mouseover(function() {
		ClearSalesMenu();

		$("#specials").addClass("specials-inactive");
		$("#email").addClass("email-active");
		$("#chat").addClass("chat-inactive");
		$("#phone").addClass("phone-inactive");

		$("#contactbottom #email-content").css("display", "block"); //remove after unify sprites for sub pages
		$("#contactbottom-left #email-content").css("display", "block");
	});

	$(".sales-menu #phone").mouseover(function() {
		ClearSalesMenu();

		$("#specials").addClass("specials-inactive");
		$("#phone").addClass("phone-active");
		$("#email").addClass("email-inactive");
		$("#chat").addClass("chat-inactive");


		$("#contactbottom #phone-content").css("display", "block");  //remove after unify sprites for sub pages
		$("#contactbottom-left #phone-content").css("display", "block");
	});

    $(".sales-menu #specials").mouseover(function() {
        ClearSalesMenu();

        $("#specials").addClass("specials-active");
        $("#phone").addClass("phone-inactive");
        $("#email").addClass("email-inactive");
        $("#chat").addClass("chat-inactive");

        $("#contactbottom #phone-content").css("display", "block");  //remove after unify sprites for sub pages
        $("#contactbottom-left #phone-content").css("display", "block");
    });


	// bottom row additional resources links
	$("#download-datasheet").click(function() {
		location.href = "/resources/datasheets/";
	});

	// resize even on the body to handle modal dialog height/scroll changes.
	$(window).resize(function() {
		adjustModal();
	});


    // Detect Flash for pages that need it
    haveReqFlash = (DetectFlashVer(8, 0, 0));


    // Network overview page: If required flash is present, show the flash map, else, show alternate content
    if (haveReqFlash){
        $('#flash-network-map').css('display', 'block');
    } else {
        $('#network-map-no-flash').css('display', 'block');
    }

    //Link event banner to event page
    $('#home-event-banner').click(function() {
       location.href = '/about/event-schedule';
    });

    /* Modal Dialogs init */
    if ($('.social-right').length) { $('.social-right').colorbox({width:"80%", height:"80%", iframe:true}); }
    if ($('#virtual-overview').length) { $('#virtual-overview').colorbox({width:"80%", height:"80%", iframe:true}); }
    if ($('.datacenteroverview').length) { $('.datacenteroverview').colorbox({width:"800px", height:"550px", iframe:true}); }
    if ($('.simplifiednetworkdiagram').length) { $('.simplifiednetworkdiagram').colorbox({width:"1085px", height:"600px", iframe:true}); }
    if ($('.networkdiagramdallas').length) { $('.networkdiagramdallas').colorbox({width:"1124px", height:"800px", iframe:true}); }
    if ($('.networkdiagramdallastwo').length) { $('.networkdiagramdallastwo').colorbox({width:"1124px", height:"800px", iframe:true}); }
    if ($('.networkdiagramdallasfive').length) { $('.networkdiagramdallasfive').colorbox({width:"1124px", height:"800px", iframe:true}); }
    if ($('.pod-network-diagram').length) { $('.pod-network-diagram').colorbox({width:"1124px", height:"800px", iframe:true}); }
    if ($('.pod-network-diagram-dualpath').length) { $('.pod-network-diagram-dualpath').colorbox({width:"1124px", height:"800px", iframe:true}); }
    if ($('.seattle-details').length) { $('.seattle-details').colorbox({width:"1124px", height:"800px", iframe:true}); }
    if ($('.wdc-details').length) { $('.wdc-details').colorbox({width:"1124px", height:"800px", iframe:true}); }
    if ($('.magnify-iphone').length) { $('.magnify-iphone').colorbox({width:"610", height:"690", iframe:true}); }
    if ($('.magnify-ipad').length) { $('.magnify-ipad').colorbox({width:"1055", height:"905", iframe:true}); }
    if ($('.magnify-winphone').length) { $('.magnify-winphone').colorbox({width:"665", height:"690", iframe:true}); }
    if ($('.wmp-demo').length) { $('.wmp-demo').colorbox({width: "600px", height: "400px", iframe:true}); }
    if ($('.flash-demo').length) { $('.flash-demo').colorbox({width: "730px", height: "500px", iframe:true}); }
    if ($('.magnify-droid').length) { $('.magnify-droid').colorbox({width: "600px", height: "710px", iframe:true}); }
    if ($('.dedicated-vs-cloud').length) { $('.dedicated-vs-cloud').colorbox({width:"900px", height:"715px", iframe:true}); }
    if ($('.execdash').length) { $('.execdash').colorbox({width:"997px", height:"1340px", iframe:true}); }
    if ($('.marketplace-screenshot-clicktale-heatmap-a').length) { $('.marketplace-screenshot-clicktale-heatmap-a').colorbox({width:"1124px", height:"800px", iframe:true}); }
    if ($('.marketplace-screenshot-clicktale-comparison').length) { $('.marketplace-screenshot-clicktale-comparison').colorbox({width:"1124px", height:"700px", iframe:true}); }
    if ($('.marketplace-screenshot-clicktale-analytics').length) { $('.marketplace-screenshot-clicktale-analytics').colorbox({width:"800px", height:"780px", iframe:true}); }
    if ($('.managed-hosting-modal-dashboard').length) { $('.managed-hosting-modal-dashboard').colorbox({width:"1075px", height:"700px", iframe:true}); }
    if ($('.globalNetworkMapOct11').length) { $('.globalNetworkMapOct11').colorbox({width:"1124px", height:"550px", iframe:true}); }
});

document.onclick = jsddm_close;


//----------- Rotating Banner functions

//this function to be used as a class.  IE: var x = new HomeBannerImage(...
function BannerImage(imgUrl, linkUrl, altText) {
    this.imgUrl = imgUrl;
    this.linkUrl = linkUrl;
    this.altText = altText;
}

//function to define a currentImage class. This is used to pass parameters as reference in the rotation banner below
function currentImage () {
    this.id = "";
}

//function to define a currentImageCounter class to also be used by reference in the below function.
function currentImageCounter () {
    this.count = 0;
}

//function to rotate images with a fade effect on multiple pages/pieces of content
function bannerRotate(currentImageHolder, currentImageCounter, banner1Id, banner1LinkId, banner2Id, banner2LinkId, bannerArray) {
    var originalBannerId = currentImageHolder.id;
    var newBannerId = "";
    var newLinkId = "";
    
    if (originalBannerId == banner1Id){
        newBannerId = banner2Id;
        newLinkId = banner2LinkId;
    } else {
        newBannerId = banner1Id;
        newLinkId = banner1LinkId;
    }
        
    $(newBannerId).attr('src', bannerArray[currentImageCounter.count].imgUrl).attr('alt', bannerArray[currentImageCounter.count].altText);
    $(newLinkId).attr('href', bannerArray[currentImageCounter.count].linkUrl);
    $(originalBannerId).css("z-index", "0");
    $(newBannerId).css("z-index", "10");
    $(newBannerId).fadeIn(1500, function(){
        $(originalBannerId).hide();
        currentImageHolder.id = newBannerId;
    });
    
    if (currentImageCounter.count == bannerArray.length-1) {
        currentImageCounter.count = 0;
    } else {
        currentImageCounter.count++;
    }
}

//----------- End Rotating Banner functions


// functions related to new subnavigation implementation

$(document).ready(function() {
    InitSubNavBoxes();
});

function InitSubNavBoxes() {
    $(".subnavContainer").mouseover(function(){
        $(this).removeClass("unselected");
        $(this).addClass("selected");
    });
    $(".subnavContainer").mouseout(function(){
        $(this).removeClass("selected");
        $(this).addClass("unselected");
    });
    $(".subnavContainer").click(function (){
        var href = $(this).children(":first").children(":first").attr("href");
        window.location = href;
    });
}

function SetSelectedSubNavBox(navBoxID) {
    $(document).ready(function() {
        $(navBoxID).removeClass("unselected");
        $(navBoxID).addClass("selected");
        $(navBoxID).unbind();
        });
}

// homepage banner rotation functions



var HomeBannerArray = [];





HomeBannerArray.push( new BannerImage("../images/banners/home_feature_flex_images.jpg", "/flexImageBeta", "Introducing Flex Images Beta" ));
HomeBannerArray.push( new BannerImage("../images/banners/home_feature_singapore-amsterdam.jpg", "/international-hosting", "Singapore and Amsterdam Data Centers" ));
HomeBannerArray.push( new BannerImage("../images/banners/home_feature_quantastor_storage.jpg", "/lp/quantastor", "QuantaStor Storage Server - Deploy your own private SAN or NAS with a powerful, dedicated storage appliance" ));
HomeBannerArray.push( new BannerImage("../images/banners/home_feature_managed-hosting.jpg", "/managed", "Managed Hosting" ));


//currentImageCounter, and currentImage are objects defined in common.js
var currentHomePageBannerNumber = new currentImageCounter();
currentHomePageBannerNumber.count = 1;

var currentHomePageBanner = new currentImage();
currentHomePageBanner.id = "#home-banner1";

function trim(val) {
    return val.replace(/^\s+|\s+$/g, "");
}

function homeBannerRotate() {
    switchHomeBannerNavButton(currentHomePageBannerNumber.count);
    //bannerRotate is a function declared in common.js above
    bannerRotate(currentHomePageBanner, currentHomePageBannerNumber, "#home-banner1", "#home-banner-a1", "#home-banner2", "#home-banner-a2", HomeBannerArray);
}

function switchBanner(targetBannerNumber){
    window.clearInterval(bannerRotateInterval);
    switchHomeBannerNavButton(targetBannerNumber);

    //Set the currentBannerNumber to the clicked button number first, then call bannerRotate manually to immediately switch the banner image upon button click.
    currentHomePageBannerNumber.count = targetBannerNumber;
    bannerRotate(currentHomePageBanner, currentHomePageBannerNumber, "#home-banner1", "#home-banner-a1", "#home-banner2", "#home-banner-a2", HomeBannerArray);

    //Re-start the auto rotation again
    bannerRotateInterval = window.setInterval("homeBannerRotate()", 7000);
}

function switchHomeBannerNavButton(targetButtonNumber) {
    var previousHomePageBannerNumber;
    
    if (currentHomePageBannerNumber.count == 0) {
        previousHomePageBannerNumber = HomeBannerArray.length - 1;
    } else {
        previousHomePageBannerNumber = currentHomePageBannerNumber.count - 1;
    }

    $("#banner-button-" + targetButtonNumber).addClass('home-banner-nav-circle-active');
    $("#banner-button-" + previousHomePageBannerNumber).removeClass('home-banner-nav-circle-active');
}

//portal login form validators
function validateportallogin()
{
    if ($('#uname').val() != "" && $('#pwd').val() != "") 
    {
        if ($('#locations').val() != "portal")
        {
            if ($('#locations').val() == "closest")
            {
                document.loginform.action = "https://vpn.softlayer.com/prx/000/http/localhost/login";
            }
            else
            {
                document.loginform.action = "https://vpn." + $('#locations').val() + ".softlayer.com/prx/000/http/localhost/login";
            }
        }
        else
        {
            document.loginform.action = 'https://manage.softlayer.com/index/index';
            $('#portalUsername').attr('value', $('#uname').val());
            $('#portalPassword').attr('value', $('#pwd').val());
        }

        return true;   
    }    
    else
        alert('Please enter a valid username and password.');
        
    return false;
}

$(function() 
{
    $('#loginform').submit(function () 
    {
        return validateportallogin();
    });

    // draw focus to the "username" textbox on load.
    $('#username').focus();
});

//functions for the social icons

$(function() 
        {
            $('.social-icon').mouseover(function()
            {
                var id = $(this).children('a:nth-child(2)').attr('id');
                $('#' + id).show();
            });
            
            $('.social-icon').mouseout(function()
            {
                var id = $(this).children('a:nth-child(2)').attr('id');
                $('#' + id).hide();
            });
        });

//IPV4 countdown functions----------------------------------------------------------------

//variables to be updated, dynamically or otherwise.
var remainingBlocks = 12;
var endDate = new Date("2011/06/05");
var reportDate = new Date("2010/10/17");
var remainingAddresses = 0;

//variables that never change.
var totalBlocks = 256;
var addressesPerBlock = Math.pow(2, 24); // 2^24 addresses per block
var ipAllocRate = 10; //for now, use 10 IP/s allocated per second.

function SetIPV4StartupAndDisplay(remaining_Blocks, report_Date, end_Date)
{
    remainingBlocks = remaining_Blocks;
    reportDate = new Date(report_Date);
    endDate = new Date(end_Date);
    DisplayIPV4Values();
}

function DisplayIPV4Values()
{
    remainingAddresses = remainingBlocks*addressesPerBlock;
    var currentDate = new Date();
    var elapsedTimeNow = currentDate.getTime() - reportDate.getTime();
    var consumedIPAddressesNow =  Math.round((ipAllocRate * (elapsedTimeNow/1000)));
    remainingAddresses -= consumedIPAddressesNow;
    var timeRemaining = endDate.getTime() - currentDate.getTime();
    var daysRemaining = 0;
    var percentRemain = 0;
    if(remainingAddresses > 0 && timeRemaining > 0 && remainingBlocks > 0)
    {
        daysRemaining = Math.floor((((timeRemaining/1000)/60)/60)/24);
        percentRemain = Math.round(((remainingBlocks/256)*100));
    }
    
    $(document).ready(function(){
        $("#blocksRemainPercent").html(percentRemain);
        $("#blocksRemain").html(remainingBlocks);
        $("#blocksTotal").html(totalBlocks);
        $("#daysRemain").html(daysRemaining);
        TimerTick();
    });
}

function TimerTick()
{
    if(remainingAddresses > 0)
    {
        remainingAddresses -= 1;
        $("#ipRemain").html( Commaize(remainingAddresses) );
        setTimeout("TimerTick()", 100);
    }
}

function Commaize(number) {
    var numberstring = String (number);
    var x = numberstring.split (".");
    var x1 = x [0];
    var x2 = x.length > 1 ? "." + x [1] : "";
    var regex = /(\d+)(\d{3})/;
    while (regex.test (x1)) {
        x1 = x1.replace (regex, "$1" + "," + "$2");
    }
    return (x1 + x2);
}

//events rotator functions--------------------------------------------------------------------------

//this function to be used as a class.  IE: var x = new SoftlayerEvent(...
function SoftlayerEvent(eventDate, location, title, url){
    this.eventDate = eventDate; 
    this.location = location;
    this.title = title;
    this.url = url;
}

var eventsArray = [];
function AddEvent(eventDate, location, title, url) {
    eventsArray.push(new SoftlayerEvent(eventDate, location, title, url));
}

function RotateEvents(){
    if(eventsArray.length == 0){
        ShowEmpty();
    }
    else {
        var index = GetRandomIndex();
        RotateInfo(eventsArray[index]);
    }
}

function ShowEmpty(){
    var emptyEvent = new SoftlayerEvent("", "", "No Events Scheduled", "/about/event-schedule/");
    SetInfo(emptyEvent);
    $("#home-event-date").hide();
    $("#home-event-location").hide();
    $("#home-event-website-url").html("View all events");
}

function RotateInfo(event){
    $("#home-event-text").slideUp("fast", function(){
        SetInfo(event);
        $("#home-event-text").slideDown("fast");
    });
}

function SetInfo(event){
    $("#home-event-url").attr("href", event.url);
    $("#home-event-title-url").attr("href", event.url);
    $("#home-event-website-url").attr("href", event.url);
    $("#home-event-name").html(event.title);
    $("#home-event-location").html(event.location);
    $("#home-event-date").html(event.eventDate);
}

var currentIndex = -1;
function GetRandomIndex(){
    //get a random index for the eventsArray.  If empty or 1, just return 0,
    //otherwise return a random index other than the current index.
    if(eventsArray.length == 1 || eventsArray.length == 0){
        return 0;
    }
    var returnIndex = -1;
    do {
        returnIndex = Math.floor ( Math.random() * eventsArray.length );
    }
    while(currentIndex == returnIndex);
    currentIndex = returnIndex;
    return returnIndex;
}

function InitEventsRotator(){
    if(eventsArray.length == 0){
        ShowEmpty();
    }
    else {
        //Show a random event.  If there is more than 1 event, rotate them out randomly every 10 seconds.
        var index = GetRandomIndex();
        currentIndex = index;
        SetInfo(eventsArray[index]);
        if(eventsArray.length > 1){
            setInterval("RotateEvents();", 10000);
        }
    }
}

function TrackPDFAnchors() {
    $("a").each(function(){
        if($(this).attr("href")) {
            var url = $(this).attr("href").toLowerCase();
            if(url.indexOf(".pdf") > 0) {
                var lastIndex = url.lastIndexOf("/");
                var pdfFileName = url.substring(lastIndex+1);
                var page = window.location.pathname;
                var id = page + "__" + pdfFileName;
                $(this).click(function(){
                    _gaq.push(['_trackPageview', id]);
                });
            }
        }
    });
}

function FixRedButtonClickEvents() {
    $(".shadowButton a").click(function(e){
        e.stopPropagation();
    });
}

function PreloadRedButtonImages() {
    if(parent.location.protocol == "http:") {
    $.preloadImages(
            "/images/misc/bottom_blackShadow.jpg", "/images/misc/left_blackShadow.jpg",
            "http://static1.softlayer.com/images/misc/bottom_blackShadow.jpg", "http://static1.softlayer.com/images/misc/left_blackShadow.jpg",
            "http://static2.softlayer.com/images/misc/bottom_blackShadow.jpg", "http://static2.softlayer.com/images/misc/left_blackShadow.jpg"
    );
}
}

$(document).ready(function(){
    InitEventsRotator();
    TrackPDFAnchors();
    FixRedButtonClickEvents();
    PreloadRedButtonImages();
});
