﻿google.setOnLoadCallback(function() {
    $(document).ready(function() {
        //initICEExplorer();
        loadRotatorImages();
    });
});

var lastXLoc = 0;
var currentXLoc = 0;
var vertSwitch = 0;
var vertSwitchLock = 0;
var rotating = true;
var clickRotate = false;
var clickRotateFirstRun = true;
var rotateDelay = 10;
var autoRotateInterval = 40;
var currentFrame = 1;
var areaCount;
var areaIndex;
var fullShowing = false;
var rotTimer;


function loadRotatorImages() {
    /*var imageUrl = $(".rotatorFrame").css('background-image').replace("001.jpg", "{holder}").replace("\"", "").replace("\"", "");
    for (var i = 2; i <= 36; i++) {
        var z = "00";
        if (i >= 10) {
            z = "0";
        }
        $("#rotatorImages").append("<li class=\"rotatorFrame\" style=\"background-image: " + imageUrl.replace("{holder}", z + i + ".jpg") + "; display: block; \"></li>");
    }*/
    jumpToFrame(1);
}


//Set the quirky frame number offset so we don't ever land on forward or back facing images
var frameLookup = [1, 13, 17, 19, 32, 35];

function initICEExplorer() {
	//Rig all of the tags etc
	
	//Kill text selection
	$("#trikeExplorer").bind('selectstart', function(e) { return $(e.target).is(':input'); });
	$(".rotateButtons").bind('selectstart', function(e) { return false; });

	areaCount = $("#trikeAreas .areaHolder");
	areaCount = areaCount.length;

	//Move the area holder HTML into the submenu
	var htmlCopy = $("#trikeAreas").clone().remove();
	$(".auto").append(htmlCopy);

	$(".areaHolder li").hide();
	$(".shortDescription").hide();
    $(".fullInformation").hide();
    $(".technicalInformation").hide();
    $("#overlay").hide();
    
    $(".areaButton").click(function() { showArea($(this).parent()); });

    //Rig the mouse co-ord grabber
    $().mousemove(function(e) {
		currentXLoc = e.pageX;
    	vertSwitch = (e.pageY < 420) ? -1 : 1;
    	//$("#status").html(e.pageX + ', ' + e.pageY + ', ' + lastXLoc + ', ' + currentFrame + ', ' + areaCount + ', ' + areaIndex);
    	if (rotating && !clickRotate) {
    		if (currentXLoc < lastXLoc - 10) {
    			rotateStep(1);
    			lastXLoc = currentXLoc;
    		}
    		if (currentXLoc > lastXLoc + 10) {
    			rotateStep(-1);
    			lastXLoc = currentXLoc;
    		}
    	}
    });

    //Only activate mouse drag if there's more than one frame
    if ($(".rotatorFrame").length > 0) {
    	$("#trikeRotator").mousedown(function() { startRotate(); });
    	//End rotation wherever the mouse is released
    	$().mouseup(function() { endRotate(); });
    }
    else {
    	$("#rotatorImages").css("cursor", "auto");
    }

    //Add mousedown events to the rotate left and right buttons
    //$("#rotateLeft").mousedown(function() { rotateLeft() });
    //$("#rotateRight").mousedown(function() { rotateRight() });

    //Add click events to the rotate left and right buttons
    $("#rotateLeft").click(function() { rotateLeft() });
    $("#rotateRight").click(function() { rotateRight() });

    rotateStep(0);
    endRotate();
    $("#trikeExplorer").css("visibility", "visible");
}

function enableShortDescriptions() {
	$("#trikeTags li").mouseenter(function() { showShortDescription(this); }).mouseleave(function() { hideShortDescription(this); });
	//$("#trikeTags li .button").mousedown(function() { showFullInformation($(this).closest("li")); });
	$("#trikeTags li").mousedown(function () { showFullInformation($(this).closest("li")); });
}

function disableShortDescriptions() {
	$("#trikeTags li").unbind();
}

function skipTag(what, direction)
{
	var theParentLi = $(what).closest("li");
	if (direction == 1) {
		if (checkInRange($(theParentLi).next())) {
			showFullInformation($(theParentLi).next());
		}
		else {
			showFullInformation($(theParentLi).parent().find("li:first"));
		}
	} else {
		if (checkInRange($(theParentLi).prev())) {
			showFullInformation($(theParentLi).prev());
		}
		else {
			showFullInformation($(theParentLi).parent().find("li:last"));
		}
	}
}

function checkInRange(what) {
	if ($(what).length >=1 ) {
		return(true);
	}
	else {
		return (false);
	}
}

function showShortDescription(what) {
	$(what).css("z-index","10");
	$(what).find(".button").css("z-index", "13");
	$(what).find(".shortDescription").show(300, function() { showOpen(what)}).css("z-index", "12");
}

function showOpen(what) {
	$(what).find(".prompt").show();
	$(what).find(".tagTitle").hide();
}

function hideShortDescription(what) {
	$(what).css("z-index", "5");
	$(what).find(".button").css("z-index", "11");
	$(what).find(".shortDescription").hide(100, function() { hideOpen(what) }).css("z-index", "10");
}

function hideOpen(what) {
	$(what).find(".prompt").hide();
	$(what).find(".tagTitle").show();
}

function showFullInformation(what) {
    //$("#overlay").hide(100);

    var newOverlayContent = $(what).find(".fullInformation").html();
    $("#overlay").html(newOverlayContent);
    //pageTracker._trackPageview(window.location.pathname + "/tag/" + $("#overlay").find("h2").text().replace(" ", "-").toLowerCase());

    if (window.location.toString().indexOf("overlay=") < 0) {
        window.location = window.location.toString().replace("#", "") + setHashTagParams("tag", $(what).attr("id").replace("tag_",""));
    }

	//Switch out the image loader link for an actual image
	var loaderLink = $("#overlay .loader");
	var loaderUrl = $(loaderLink).attr("href");
	var loaderAlt = $(loaderLink).text();

	if (loaderUrl) {
	    if (loaderUrl.indexOf(".jpg") >= 1) {
	        $(loaderLink).replaceWith('<a href="' + loaderUrl.replace("overlay","full") + '" target="_blank"><img src="' + loaderUrl + '" alt="' + loaderAlt + '" class="overlayImage"></a>');
	    } else {
	        /*$("#embeddedVideo").remove();
	        $(loaderLink).replaceWith('<div id="embeddedVideo"></div>');
	        var flashvars = {
	    };
	    var params = {
	        allowFullScreen: "true",
	        allowScriptAccess: "always"
	    };
	    var attributes = {
	        id: "embeddedVideoPlayer",
	        name: "embeddedVideoPlayer"
	    };
	    swfobject.embedSWF(loaderUrl, "embeddedVideo", "960", "720", "9.0.0", null, flashvars, params, attributes);*/
	}
}

	showOverlay();
	
    $("#overlay .closeButton").unbind().click(function() { hideFullInformation(this); });
    $("#overlay .showFI").click(function() { showFurtherInformation(this); });
    $("#overlay .showTI").click(function() { showTechnicalInformation(this); });

    //Add click events to the next/back buttons
    $("#overlay .back").click(function() { skipTag(what, -1) });
    $("#overlay .next").click(function() { skipTag(what, 1) });

    fullShowing = true;
    hideArea();
}

function hideFullInformation(what) {
	hideOverlay();

    fullShowing = false;

    var areaHolder = $("#area" + (areaIndex+1));
    showArea(areaHolder); 
}

function showFurtherInformation(what) {
    $(what).closest(".text").find(".technicalInformation").hide();
    $(what).closest(".text").find(".furtherInformation").show();
}

function showTechnicalInformation(what) {
	$(what).closest(".text").find(".technicalInformation").show();
	$(what).closest(".text").find(".furtherInformation").hide();
}

function showArea(what) {
	$("#trikeAreas .areaHolder").removeClass("current");
    var currentAreaDiv = what;
    $(currentAreaDiv).addClass("current");

    areaIndex = $(currentAreaDiv).attr("id").split("area")[1]-1;
    //Use a lookup, not divider
    //currentFrame = Math.ceil(areaIndex * (36 / areaCount));
    currentFrame = frameLookup[areaIndex];
    jumpToFrame(currentFrame);
    
    var newTags = $(what).find("ul").html();
    $("#trikeTags").html(newTags);
    $("#trikeTags li").show(300);
    enableShortDescriptions();
}

function hideArea() {
    $("#trikeTags li").hide(100);
}

function startRotate() {
	if (!fullShowing) {
		vertSwitchLock = vertSwitch;
        lastXLoc = currentXLoc;
        rotating = true;
        hideArea();
    }
}

function endRotate() {
	if (!fullShowing && rotating) {
		//Stop the animation timer
		clearInterval(rotTimer);
		rotateDelay = 2;
        
        lastXLoc = currentXLoc;
        rotating = false;
        clickRotate = false;
        var areaHolder = $("#area" + (areaIndex+1));
        showArea(areaHolder);
    }
}

function rotateStep(direction) {
	currentFrame += (direction * vertSwitchLock)

    if (currentFrame < 0) {
        currentFrame = 35;
    }
    if (currentFrame > 35 ) {
        currentFrame = 0;
    }

    jumpToFrame(currentFrame);
}

function jumpToFrame(index) {
	$("#rotatorImages li").not("#rotatorImages li:eq(0)").hide();
    $("#rotatorImages li:eq(" + index + ")").show();
    
    //Highlight the current area
    //areaIndex = Math.floor(currentFrame / (36 / areaCount));
    //Loop until we find the closest frame lookup
    areaIndex = -1;
    var currentFrameOffset = currentFrame;
    do
    {
    	areaIndex = $.inArray(currentFrameOffset,frameLookup);
    	currentFrameOffset--;
    	if (currentFrameOffset < 0) {
    		currentFrameOffset = 35;
    	}
    	if (currentFrameOffset > 35) {
    		currentFrameOffset = 0;
    	}	
	}
	while (areaIndex == -1);
    
    $("#trikeAreas .areaHolder").removeClass("current");
    $("#area" + (areaIndex + 1)).addClass("current");


    if (openTag) {
        var tagToOpen = $("#tag_" + getUrlVars()["value"]);
        if ($(tagToOpen).length > 0) {
            showFullInformation(tagToOpen);
        }
        else {
            window.location = window.location.toString().split("#")[0] + "#";
        }
    }
    //$("#status").html(index);
}

function rotateLeft() {
	clickRotate = true;
	clickRotateFirstRun = true;
	startRotate();
	rotTimer = (setInterval(function() { autoRotateStep(1) }, autoRotateInterval));
}

function rotateRight() {
	clickRotate = true;
	clickRotateFirstRun = true;
	startRotate();
	rotTimer = (setInterval(function() { autoRotateStep(-1) }, autoRotateInterval));
}

function autoRotateStep(direction) {
	if (($.inArray(currentFrame, frameLookup) == -1) || clickRotateFirstRun == true) {
		rotateStep(direction)
		
		//Clear the interval and slow it down for some deceleration
		clearInterval(rotTimer);
		rotTimer = (setInterval(function() { autoRotateStep(direction) }, autoRotateInterval + rotateDelay));
		rotateDelay = rotateDelay * 1.5;
	}
	else {
		endRotate();
	}
	clickRotateFirstRun = false;
}
