/*
Functions for navigating website, including nav bar rollovers
and AJAX calls to load in new content.
*/

// keep track of if video "drawer" is visible or not
var videoOut = false;
var bNavActive = false;
var drawerAnimating = false;
// height of top header bar
var headerHeight = 100;
// video drawer height
var videoHeight = 214;
var footer;
var transitioning = false;
var animationTime = 1000;
var collections;
var currentCollectionIndex;
var pageCats = {
    home_men: 29,
    home_women: 33,
    boards_men: 27,
    boots_men: 2,
    ropes_men: 3,
    handles_men: 4,
    vests_men: 5,
    accessories_men: 6,
    illuminati_men: 39,
    boards_women: 7,
    boots_women: 8,
    ropes_women: 9,
    handles_women: 10,
    vests_women: 11,
    accessories_women: 12,
    illuminati_women: 40,
    dealer_locator_men: 30,
    the_brand_men: 32,
    downloads_men: 31,
    brochure_men: 29,
    dealer_locator_women: 34,
    the_brand_women: 36,
    downloads_women: 35,
    brochure_women: 29,
    where_to_ride_men: 30,
    where_to_ride_women: 34
}
// dictionary of all pages that can be loaded into main content area
var pages = {
	boards_men: "pages/products_boards.aspx?id=1&g="+gender.toLowerCase(),
	boots_men: "pages/productsBoots2.aspx?id=2&g="+gender.toLowerCase(),
	ropes_men: "pages/products.aspx?id=3&o=ropes&g="+gender.toLowerCase(),
	handles_men: "pages/products.aspx?id=4&o=handles&g="+gender.toLowerCase(),
	vests_men: "pages/products.aspx?id=5&o=vests&g="+gender.toLowerCase(),
	accessories_men: "pages/productsSoft.aspx?id=6&g="+gender.toLowerCase(),
	illuminati_men: "pages/collection.aspx?id=-1&g="+gender.toLowerCase(),
	boards_women: "pages/products_boards.aspx?id=7&g="+gender.toLowerCase(),
	boots_women: "pages/productsBoots2.aspx?id=8&g="+gender.toLowerCase(),
	ropes_women: "pages/products.aspx?id=9&o=ropes&g="+gender.toLowerCase(),
	handles_women: "pages/products.aspx?id=10&o=handles&g="+gender.toLowerCase(),
	vests_women: "pages/products.aspx?id=11&o=vests&g="+gender.toLowerCase(),
	accessories_women: "pages/productsSoft.aspx?id=12&g="+gender.toLowerCase(),
	illuminati_women: "pages/collection.aspx?id=-1&g="+gender.toLowerCase(),
	dealer_locator_men: "pages/mapframe.aspx?g=" + gender.toLowerCase(),
	the_brand_men: "pages/brand.aspx?g=" + gender.toLowerCase(),
	downloads_men: "pages/downloads.aspx?g=" + gender.toLowerCase(),
	brochure_men: "pages/misc/brochure.html?g=" + gender.toLowerCase(),
	dealer_locator_women: "pages/mapframe.aspx?g="+gender.toLowerCase(),
	the_brand_women: "pages/brand.aspx?g=" + gender.toLowerCase(),
	downloads_women: "pages/downloads.aspx?g=" + gender.toLowerCase(),
	brochure_women: "pages/misc/brochure.html?g=" + gender.toLowerCase(),
	where_to_ride_men: "pages/WhereToRide.aspx?g=" + gender.toLowerCase(),
	where_to_ride_women: "pages/WhereToRide.aspx?g=" + gender.toLowerCase()
};

var currentCollectionPage;

var backgrounds;

// array that stores all the nav elements, in order,
// so we can determine the direction of the swiping animation
var navOrder;
// stores the path of the currently displayed external page
var currentPage;

/*
Setup navigation elements
*/
function initNav() {
	$("#header").css("height", headerHeight);
	setupBackgrounds();
	// make sure all transparent backgrounds are correct size
	updateTransparentBackgrounds();
	setupPopouts();
	setupTopNav();
	handleResize();
	$(window).resize(handleResize);
}

/*
Setup the "drawers" that user can slide over.
*/
function setupPopouts() {
	// add listeners to close video drawer
	$('#ronixTv').click(toggleVideo);
	$('#video .closeButton').click(toggleVideo);

	footer = $('#footer');
	var popoutElements = $('#footer .popout');
	for (var i = popoutElements.length - 1; i >= 0; i--){
		var popout = $(popoutElements[i]);
		if(!bTouchScreen) {
			// add event listeners for the mouse over bottom drawers
			popout.hover(handlePopoutOver, handlePopoutOut)
		} else {
			popout.click(handlePopoutClick);
		}
	};
	setupCollections();
}

function setupCollections() {
	collections = $('.collections .collection');
	$('.collections .collection').hide();
	$('.collections .collection').first().show();
	currentCollectionIndex = 0;
	$('.collections .collection').first().addClass('current');
	$('.collections .left_arrow').click(prevCollection);
	$('.collections .right_arrow').click(nextCollection);
	$('.collections .collection a').click(loadCollection);
}

function prevCollection() {
	if (currentCollectionIndex <= 0) {
		currentCollectionIndex = collections.length - 1;
	} else {
		currentCollectionIndex--;
	}
	showCollection($(collections[currentCollectionIndex]), $('.collections .current'));
}

function nextCollection() {
	if (currentCollectionIndex >= collections.length - 1) {
		currentCollectionIndex = 0;
	} else {
		currentCollectionIndex++;
	}
	showCollection($(collections[currentCollectionIndex]), $('.collections .current'));
}

function showCollection(newCollection, oldCollection) {
	$(oldCollection).hide();
	$(oldCollection).removeClass('current');
	$(newCollection).fadeIn();
	$(newCollection).addClass('current');	
}

function loadCollection() {
	var pageName = $(this).attr('id');
	var url = collectionPages[pageName];
	for (i in collectionPagesOrder) {
		if (collectionPagesOrder[i] == url) {
			currentCollectionPage = i;
		}
	}
	loadPage(url);
}


function nextCollectionPage() {
    //console.log(currentCollectionPage);
	if (currentCollectionPage >= collectionPagesOrder.length - 1) {
		currentCollectionPage = 0;
		loadPage(collectionPagesOrder[currentCollectionPage], null, 1);
	} else {
		currentCollectionPage++;
		loadPage(collectionPagesOrder[currentCollectionPage], null, 1);
	}
}

function previousCollectionPage() {
    //console.log(currentCollectionPage);
	if (currentCollectionPage <= 0) {
		currentCollectionPage = collectionPagesOrder.length - 1;
		loadPage(collectionPagesOrder[currentCollectionPage], null, -1);
	} else {
		currentCollectionPage--;
		loadPage(collectionPagesOrder[currentCollectionPage], null, -1);
	}
}

/*
Setup main navigation links on top left.
*/
function setupTopNav() {
	// make selected nav item have gold text
	var navName = $("#nav .selected img").attr("id");
	$("#nav .selected img").attr("src", "images/nav/"+navName+"_hover.png");
	navOrder = new Array();
	var navElements = $('#nav img');
	for (var i = 0; i < navElements.length; i++) {
		var navLink = $(navElements[i]);
		navLink.mouseenter(handleNavOver);
		navLink.mouseleave(handleNavOut);
		if (!navLink.hasClass('ignore')) {
			navLink.click(handleNavClick);
		}
		navOrder.push(pages[navLink.attr("id")]);
    }

    $("#gotoBrand").click(function () {
        navName = $(this).attr("navName");
        var pageURL = pages[navName];
        prevPage = eval("pages." + navName);

        CurrentBackgroundID = pageCats[navName];
        initBackground();
        loadPage(pageURL);
    });
}

/*
Setup large background picture.
*/
function setupBackgrounds() {
	backgrounds = $('.background');
	backgrounds.hide();
	$(backgrounds[0]).show();
	$(backgrounds[0]).addClass('selected_background');
}

/*
Fades in a new random background image.
*/
function changeBackground() {
    if (backgrounds.length > 1) {
        var newBackground = backgrounds[Math.floor(Math.random() * backgrounds.length)];
        while ($(newBackground).hasClass('selected_background')) {
            var newBackground = backgrounds[Math.floor(Math.random() * backgrounds.length)];
        }
        $(newBackground).css('z-index', -110);
        $(newBackground).show();
        $('.selected_background').fadeOut(function() {
            $('.selected_background').removeClass('selected_background');
            $(newBackground).addClass('selected_background');
            $(newBackground).css('z-index', -100);
        });
    }
}
function popitup(url) {
    newwindow = window.open('/_xml/img.aspx?url='+url, 'name', ', scrollbars=1, height=600,width=600');
    if (window.focus) { newwindow.focus() }
    //return false;
}

/*
Loads new content with AJAX into the
current page, and animates it.
*/
function loadPage(pageURL, callback, direction) {
	$('#tooltip').fadeOut();
	$.tooltip.block();
	var oldNavElement = $('#nav .selected');
	var oldNavName = oldNavElement.children("img").attr("id");
	oldNavElement.children("img").attr("src", "images/nav/"+oldNavName+".png");
	oldNavElement.removeClass('selected');

	//console.log("PageURL: " + pageURL);
	//changeBackground();
	// what's the URL of the new page from the dictionary?
	if (pageURL != currentPage) {
	    //Hide that movie player or the site will freak out in IE
        if (isIE) {
	        $('.video').hide();
	    }
	    if ($("#video").css('height') == videoHeight+'px') {
            toggleVideo();
        }
        urchinTracker(pageURL);
		if (!direction) {
			direction = getDirection(currentPage, pageURL);
        }

		if (pageURL && !transitioning) {
			transitioning = true;
			// add a new wrapper div to hold the new content
			$("#page_loader").append('<div id="new_main_content_wrapper" class="content_wrapper"> </div>');
			var newContent = $("#new_main_content_wrapper");
			var windowWidth = $(window).width() / 2;
			// put the new content wrapper off screen
			newContent.css("left", direction * windowWidth/2);
		//	newContent.css("opacity", 0); // doesn't work in IE
			// grab the current content wrapper
			var oldContent = $("#main_content_wrapper");
			currentPage = pageURL;
			//console.log(oldContent);
			oldContent.animate({ left: (-1) * direction * windowWidth / 2 }, animationTime / 2, "swing", function() {
			    oldContent.remove();
			    $('#loading_graphic').show();
			    newContent.load(pageURL, function() {
			        $('#loading_graphic').hide();
			        // make sure all the transparentBackground divs are working correctly
			        updateTransparentBackgrounds();
			        if (callback) {
			            callback();
			        }
			        handleResize();
			        // and animate the new stuff in
			        newContent.animate({ left: 0 }, animationTime, "easeOutBack", function() {
			            // now that it's the new stuff, we need to rename it
			            newContent.removeAttr("id");
			            newContent.attr("id", "main_content_wrapper");
			            transitioning = false;
			            handleResize();
			            $.tooltip.block();
			        });
			    });
			});
		}
	}
}

/*
Returns either 1 or -1, which represents
the direction the pages should swipe based
on their order in the nav list.
*/
function getDirection(oldPage, newPage) {
	for (var i = 0; i < navOrder.length; i++) {
		if (navOrder[i] == oldPage) {
			return 1;
		} else if (navOrder[i] == newPage) {
			return -1;
		}
	}
	return 1;
}

/* 
Makes sure that all transparent backgrounds match the width
and height of their parent divs. the transparent background
must be a seperate div than the content. see this page for info:
http://www.impressivewebs.com/css-opacity-that-doesnt-affect-child-elements/
*/
function updateTransparentBackgrounds() {
	var transparentBackgrounds = $('.transparentBackground');
	for (var i = transparentBackgrounds.length - 1; i >= 0; i--) {
		var tb = $(transparentBackgrounds[i]);
		// find width and height of parent
		var width = tb.parent().width();
		var height = tb.parent().height();

		var browserwidth = $(window).width();
		var browserheight = $(window).height();
		// set transparent background to match parent
		tb.css("width", width);
		tb.css("height", height);

	}
}

// Handles resizing the windows.
function handleResize() {
	var nWidth = $(window).width();
	var nHeight = $(window).height();
	
	footer.css("width", nWidth - 40);
	$('#page_loader').css("height", nHeight);
	$('#main_content_wrapper').css("width", nWidth);
	$('#header').css("width", nWidth);
	$('#header #top').css("width", nWidth );
	var headerLeftPadding = 16;
	var headerRightPadding = 50 + 100;
	$('#header #topNav, #header #bottomNav').css("width", nWidth - (headerLeftPadding + headerRightPadding));
	$('.content_wrapper').css('top', Math.max(nHeight/2 - $('.content_wrapper').height()/2, 95));
	$('#loading_graphic').css('width', nWidth);
	$('#loading_graphic').css('top', nHeight/2);
	$('#header #top #bg').css('width', nWidth - 209 - 290);
	$('#logo_container').css('top', nHeight/2 - $('#logo_container').height()/2);
	$('#logo_container').css('left', nWidth/2 - $('#logo_container').width()/2);
	updateTransparentBackgrounds();
}


/*
Swipe video drawer in / out.
*/
function toggleVideo() {
	if (videoOut) {
	    videoOut = false;
	    $("#videoButton").attr("src", $("#videoButton").attr("src").replace("_close", "_open"));
	    if (!isIE) {
	        $("#video").animate({ height: 0 }, 200, function () {
	            $("#video .video_holder").html("");
	        });
	    } else {
	        $("#video").css('height', 0);
	        setTimeout('$("#video .video_holder").html("");',200);
	    
	    }
	} else {
	    videoOut = true;
	    $("#videoButton").attr("src", $("#videoButton").attr("src").replace("_open", "_close"));
	    
	    if (!isIE) {
	        $("#video").animate({ height: videoHeight }, 200, function () {
	            $("#video .video_holder").html(Site_RonixTV_embed);
	        });
	    } else {
	        $("#video").css('height', videoHeight);
	        setTimeout('$("#video .video_holder").html(Site_RonixTV_embed);', 100);
	    }
		
	}
}

/*
Called when mouse rolls over top nav link.
*/
function handleNavOver() {
	var navName = $(this).attr("id");
	$(this).attr("src", "images/nav/"+navName+"_hover.png");
}

/*
Called when mouse rolls out of top nav link.
*/
function handleNavOut() {
  //  console.log("out");
	var navName = $(this).attr("id");
	if (pages[navName] != currentPage) {
		$(this).attr("src", "images/nav/"+navName+".png");
	}
}
var prevPage;
/*
Called when user clicks on top nav link.
*/
function handleNavClick() {
	if (!transitioning) {
		var navName = $(this).attr("id");
		var pageURL = pages[navName];
		prevPage=eval("pages."+navName);
		if (CurrentSectionIdx) {
		    CurrentSectionIdx = 0;
		}
		CurrentBackgroundID = pageCats[navName];
		initBackground();
		loadPage(pageURL);		
		$(this).attr("src", "images/nav/"+navName+"_hover.png");
		$(this).parent().addClass('selected');
	}
}

/*
Called when mouse is over bottom drawer (collections and news).
*/
function handlePopoutOver() {
	bNavActive = true;
	drawerAnimating = true;
	$(this).stop();
	$(this).animate( { height:187 }, 600, "easeOutQuart", function() {
		drawerAnimating = false;
	});
}

/*
Called when mouse leaves bottom drawer.
*/
function handlePopoutOut() {
	$(this).stop();
	bNavActive = false;
	drawerAnimating = true;
	$(this).animate( { height:30 }, 200, function() {
		drawerAnimating = false;
	});
}

/*
Called when user clicks on bottom drawer.
*/
function handlePopoutClick() {
	if(bNavActive) {
		handleNavOut();
	} else {
		handleNavOver();
	}
}

