dojo.require("dojo.fx");
dojo.require("dojox.fx");
dojo.require("dojox.analytics.Urchin");
dojo.require("dojox.timing._base");

var movie = null;
var movieController = null;

function fullUrlForRelativeUrl(url) {
    var anchor = dojo.create("div", { innerHTML: "<a href=\"" + url + "\">&nbsp;</a>" });
    return anchor.childNodes[0].href;
}

var tracker = {
    dojoTracker: null,
    toTrack: [], 
    trackPageView: function (url) {
    	var localUrlMatch = fullUrlForRelativeUrl(url).match(/http:\/\/[^/]+(\/.*)/);
    	if(localUrlMatch) {
	        var localUrl = localUrlMatch[1];
	        if(this.dojoTracker) {
	            this.dojoTracker.trackPageView(localUrl);
	        } else {
	            this.toTrack.push(localUrl);
	        }
	        clicky.log(localUrl, null, 'pageview');
        }
    },
    trackerDidLoad: function(trackerIn) {
        trackerIn.trackPageView();
        this.dojoTracker = trackerIn;
        dojo.forEach(this.toTrack, function (url) {
            tracker.trackPageView(url);
        });
        this.toTrack = null;
    }
}; 

dojo.addOnLoad(
    function() {
        clicky.init(153531);   
        new dojox.analytics.Urchin({ acct: "UA-8544308-5", 
                                 GAonLoad: function(){ tracker.trackerDidLoad(this); } });
        
        // These crazy machinations are because this works differently
        // in Safari, Firefox and IE...
        movie = dojo.byId("qtMovie");
        if(movie) {
            movieController = dojo.byId("qtMovieEmbed");
            if(!movieController) {
                movieController = movie;
            }
        }
        if(movieController) { // still null if QT is not available.
            try {
                if(dojo.isIE) {
                    movie.attachEvent("onqt_play", function() { movieDidPlay(movieController); } );
                    movie.attachEvent("onqt_ended", function() { movieDidEnd(movieController); } );
                } else {
                    dojo.connect(movie, "qt_play", function() { movieDidPlay(movieController); } );
                    dojo.connect(movie, "qt_ended", function() { movieDidEnd(movieController); } );
                }
                movieController.SetResetPropertiesOnReload(false);
            } catch (e) {
                // We're probably on a linux machine without
                // full QT support.  We'll jsut stop trying
                // to use the movie.
                movieController = null;
            }
        }        
        
        dojo.query(".feature", "features").onclick(featureClicked);
        dojo.query(".feature h4", "features").onmouseover(featureTitleMouseOver).onmouseout(featureTitleMouseOut);
        
        dojo.query("#learnMoreLink")
            .onclick(learnMoreLinkOnClick);
        dojo.query("#backLink")
            .onclick(learnMoreLinkOnClick);  
            
        //if(!suppress_hhgg) {
        //	hhggMarketingLoad();
        //}
        
        dojo.query("#appstorelink")
        	.attr("href", outgoing_links['eucalyptus-link']);

    }
)

function localMovieURLForFeatureName(featureName)
{
    if(featureName == "Launching" || featureName == "FastStart") {
        featureName = featureName + "1.1";
    }
    return fullUrlForRelativeUrl("Video/" + featureName + ".mp4");
}

function movieURLForFeatureName(featureName) 
{
    var url = localMovieURLForFeatureName(featureName);
    var matches = url.match(/http:\/\/eucalyptusapp\.com\/.*\/([^/]+\.[^/]+)$/);
    if(matches) {
        url = "http://mediaandth.ingsmadeoutofotherthin.gs.s3.amazonaws.com/" + matches[1];
    }
    return url;
}

function featureNameForMovieURL(movieURL) 
{
    var featureFilename = movieURL.slice(movieURL.lastIndexOf("/") + 1);
    return featureFilename.slice(0, featureFilename.lastIndexOf("."));
}

function movieDidPlay(movie){    
    tracker.trackPageView(
        localMovieURLForFeatureName(
            featureNameForMovieURL(movieController.GetURL())
        )
    );
}

function movieDidEnd(movie) {
    selectNextFeature();
}

function playMovieForFeature(featureDiv) {
    if(movieController) {
        var newFeatureName = featureDiv.id.match(/feature-(.*)/)[1];
        var currentMovieFeatureName = featureNameForMovieURL(movieController.GetURL());
        if(currentMovieFeatureName != newFeatureName) {
            movieController.SetResetPropertiesOnReload(false);
            movieController.SetURL(movieURLForFeatureName(newFeatureName));
        }
    }
}

function selectNextFeature() {
    if(!selectFeature.isAnimating) {
        var oldFeatureDiv = dojo.query(".selected", "features")[0];
        var newFeatureDivs = dojo.query("#" + oldFeatureDiv.id + " + .feature");
        var newFeatureDiv;
        if(newFeatureDivs.length) {
            newFeatureDiv = newFeatureDivs[0];
        } else {
            newFeatureDiv = dojo.query(".feature", "features")[0];
        }
        selectFeature(newFeatureDiv);
    }
}

function selectFeature(newFeatureDiv) {
    if(!selectFeature.isAnimating) {
        var oldFeatureDiv = dojo.query(".selected", "features")[0];
        if(oldFeatureDiv != newFeatureDiv) {
            selectFeature.isAnimating = true;
            var oldDescriptionDiv = dojo.query(".description", oldFeatureDiv)[0];
            var newDescriptionDiv = dojo.query(".description", newFeatureDiv)[0];

            var height = dojo.style(oldDescriptionDiv, "height");

            var hideAnim = dojox.fx.wipeTo( { node: oldDescriptionDiv, height: 0 } );
            var revealAnim = dojox.fx.wipeTo( { node: newDescriptionDiv, height: height } );
                    
            var mainAnim = dojo.fx.combine([hideAnim, revealAnim]);
            dojo.connect(mainAnim, "onEnd", 
                         function() {
                             selectFeature.isAnimating = false;
                         });
            mainAnim.play();
            playMovieForFeature(newFeatureDiv);
                                         
            dojo.removeClass(oldFeatureDiv, "selected");
            dojo.addClass(newFeatureDiv, "selected");
            removeArrowFrom(newFeatureDiv);
        }
    }
}

function featureClicked(eventObj) {
    selectFeature(eventObj.currentTarget);
}

function featureTitleMouseOver(eventObj) {
    var titleNode = eventObj.currentTarget;
    if(!dojo.hasClass(titleNode.parentNode, "selected")) {
        dojo.fadeIn({ duration: 200, node: dojo.create("div", { "class": "arrow", innerHTML:" "}, titleNode, "beginning") }).play();

    }
}

function removeArrowFrom(titleNode) {
    dojo.query(".arrow", titleNode).forEach(
        function(arrowNode) {            
            dojo.fadeOut({
                        duration: 200, 
                        node: arrowNode,
                        onEnd: function() { 
                                var parent = arrowNode.parentNode; if(parent) parent.removeChild(arrowNode); 
                            }
                        }).play();
        }
    );
}

function featureTitleMouseOut(eventObj) {
    var titleNode = eventObj.currentTarget;
    if(!dojo.hasClass(titleNode.parentNode, "selected")) {
        removeArrowFrom(titleNode);
    }
}

function learnMoreLinkOnClick(eventObj) {   
    if(!learnMoreLinkOnClick.isAnimating) {
        var learnMoreLink = dojo.byId("learnMoreLink");
        var backLink = dojo.byId("backLink");
        var learnMoreDiv = dojo.byId("learnMore");
        if(dojo.style(learnMoreDiv, "visibility") == "hidden") {
            var fullWidth = dojo.style(learnMoreDiv, "width");
            var xPosition = dojo.style(learnMoreDiv, "left");
            var yPosition = dojo.style(learnMoreDiv, "top");
            dojo.style(learnMoreDiv, "width", "1px");
            dojo.style(learnMoreDiv, "left", fullWidth+"px");
            dojo.style(learnMoreDiv, "visibility", "visible");
            
            var wipe = dojox.fx.wipeTo( { node: learnMoreDiv, width: fullWidth } );
            var slide = dojo.fx.slideTo( { node: learnMoreDiv, 
                                           left: xPosition, 
                                            top: yPosition} ); 
            dojo.style(backLink, "opacity", 0);
            dojo.style(backLink, "visibility", "visible");
            var fadeOut = dojo.fadeOut( { node: learnMoreLink } );
            var fadeIn = dojo.fadeIn( { node: dojo.byId("backLink") } );
            var mainAnim = dojo.fx.combine([wipe, slide, fadeIn, fadeOut]);
            dojo.connect(mainAnim, "onEnd", 
             function() {
                 dojo.style(learnMoreLink, "visibility", "hidden");
                 learnMoreLinkOnClick.isAnimating = false;
             });
            learnMoreLinkOnClick.isAnimating = true;
            mainAnim.play();
            
            tracker.trackPageView("LearnMore.html");
        } else {
            var fullWidth = dojo.style(learnMoreDiv, "width");
            var xPosition = dojo.style(learnMoreDiv, "left");
            var yPosition = dojo.style(learnMoreDiv, "top");
            var wipe = dojox.fx.wipeTo( { node: learnMoreDiv, width: 1 } );
            var slide = dojo.fx.slideTo( { node: learnMoreDiv, 
                                           left: fullWidth, 
                                            top: yPosition} ); 
            dojo.style(learnMoreLink, "opacity", 0);
            dojo.style(learnMoreLink, "visibility", "visible");
            var fadeIn = dojo.fadeIn( { node: learnMoreLink } );
            var fadeOut = dojo.fadeOut( { node: dojo.byId("backLink") } );
            var mainAnim = dojo.fx.combine([wipe, slide, fadeIn, fadeOut]);
            dojo.connect(mainAnim, "onEnd", 
             function() {
                 dojo.style(backLink, "visibility", "hidden");
                 dojo.style(learnMoreDiv, "visibility", "hidden");
                 dojo.style(learnMoreDiv, "width", fullWidth+"px");
                 dojo.style(learnMoreDiv, "left", xPosition);

                 learnMoreLinkOnClick.isAnimating = false;
             });
            learnMoreLinkOnClick.isAnimating = true;
            mainAnim.play();
        }
    }
}

function goHHGG() {
	tracker.trackPageView(outgoing_links['sale-track']);
	window.location = outgoing_links['sale-link'];
}

function hhggMarketingLoad() {
	var button = dojo.create("img", { "id":"HHGGButton" });
	dojo.connect(button, "onload", animateHHGG);
	dojo.connect(button, "onclick", goHHGG);
	dojo.place(button, "logo", "first");
	dojo.attr(button, "src", "Images/OnSaleStraight.png");
}

function getTransformProperty(element) {
    var properties = ['transform', 'WebkitTransform', 'MozTransform'];
    var p;
    while (p = properties.shift()) {
        if (typeof element.style[p] != 'undefined') {
            return p;
        }
    }
    return false;
}

function animateHHGG() {
	var button = dojo.byId("HHGGButton");
	
	var timer = new dojox.timing.Timer(1000.0 / 30.0);

	timer.initialZoom = 0.0;
	timer.grow = 0.25;	
	timer.moveX = 0.75;	
	timer.moveY = 0.25;	
	timer.rotate = 0.25;
	timer.transformProperty = getTransformProperty(button);
	timer.baseX = dojo.style(button, "left");
	timer.baseY = dojo.style(button, "top");
	//console.log(timer.baseX, timer.baseY);
	timer.onTick = function () {
		this.rotate += 1.0/249.0;
		var scaledRotate = (Math.cos(Math.PI * this.rotate * 2.0) + 1.0) / 2.0;
		if(this.transformProperty) {
			button.style[this.transformProperty] = "rotate(" + (-9.0 + (scaledRotate * 18.0)) + "deg)";
		}
		
		this.grow += 1.0/159.0;
		var scaledgrow = (Math.cos(Math.PI * this.grow * 2.0) + 1.0) / 2.0;
		var pixels = (-3.0 + (scaledgrow * 6.0));
		var x = (-pixels / 2.0);
		var y = (-pixels / 2.0);
		pixels += 102;
		
		this.moveX += 1.0 / 879.0;
		var scaledMoveX = (Math.cos(Math.PI * this.moveX * 2.0) + 1.0) / 2.0;
		this.moveY += 1.0 / 303.0;
		var scaledMoveY = (Math.cos(Math.PI * this.moveY * 2.0) + 1.0) / 2.0;

		x += (-85.0 + (scaledMoveX * 170.0))
		y += (-16.0 + (scaledMoveY * 32.0))

		this.initialZoom += 1.0 / 75.0;
		var scaledZoom = Math.sin(2.0 * Math.PI * this.initialZoom - (Math.PI / 2.0))
		scaledZoom *= (this.initialZoom + 1.0) / Math.pow(this.initialZoom+1.0, 6.0);
		scaledZoom += 1.0; 

		var newPixels = pixels * scaledZoom;
		x += (pixels - newPixels) / 2.0;
		y += (pixels - newPixels) / 2.0;
		pixels = newPixels;

		dojo.style(button, "left", this.baseX + x + "px");
		dojo.style(button, "top", this.baseY + y + "px");
		dojo.style(button, "width", pixels + "px");
		dojo.style(button, "height", pixels + "px");
		
        dojo.style(button, "visibility", "visible");
	}; 
	timer.start(); // start the timer */
}