/////////////
// Actions //
/////////////

// Set Globals
var thisPage; // returned from thisPageName()
var currentLocationUri = window.location.pathname; // current page script
var userIp;

/*
* get IP
*/
function getip(json){
	userIp = json.ip;
}

// SET THE CURRENT LOCATION URI BASED ON THE WINDOW.LOCATION.PATHNAME
var uriSplit = currentLocationUri.split("/");
(uriSplit[2] != undefined)? currentLocationUri = "/" + uriSplit[1] + "/" + uriSplit[2] : currentLocationUri = "/" + uriSplit[1];
(currentLocationUri == "/")? currentLocationUri = "/home" : currentLocationUri = currentLocationUri;


$(window).load(function() {
	if($('#slider').length == 0) {} else {
		$('#slider').nivoSlider({
	        effect:'sliceDown', //Specify sets like: 'fold,fade,sliceDown,random'
	        slices:8,
	        animSpeed:1250, //Slide transition speed
	        pauseTime:4500,
	        startSlide:0, //Set starting Slide (0 index)
	        directionNav:true, //Next & Prev
	        directionNavHide:true, //Only show on hover
	        controlNav:true, //1,2,3...
	        controlNavThumbs:false, //Use thumbnails for Control Nav
	        controlNavThumbsFromRel:false, //Use image rel for thumbs
	        //controlNavThumbsSearch: '.jpg', //Replace this with...
	        //controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src
	        keyboardNav:true, //Use left & right arrows
	        pauseOnHover:true, //Stop animation while hovering
	        manualAdvance:false, //Force manual transitions
	        captionOpacity:0.8, //Universal caption opacity
	        beforeChange: function(){},
	        afterChange: function(){},
	        slideshowEnd: function(){} //Triggers after all slides have been shown
	    });
	}
});

// Document Ready
$(document).ready( 
	function() {
	
		// Get page name
		thisPage = thisPageName();
		
		// Add class name to each table; not a permanent solution
		tableClasses(thisPage);
		
		// If homepage, setup jCarousel, etc.
		if (thisPage == 'default.asp' || thisPage == '') {
			setupJcarousel();
			changeBgColor();
			var contentArea = $('#content_area');
			contentArea.css('margin','0px auto').css('padding','0px').css('width','980px'); /* removes extra margin and padding from content area on homepage */
			
		} else if(thisPage == 'login.asp') {
			blackBackground(); // set content_area bg to black
			loginPageLayout(); // set login page look & feel
			
		} else if(thisPage == 'myaccount.asp') {
			myAccountPageLayout();
			
		} else if(thisPage == 'orders.asp') {
			
		}
		
		
		// LATEST NEWS
		if (currentLocationUri == '/category-s/88.htm') {
			removeAddToCartButton();
			removeProductLink();
			
		// ONE PAGE CHECKOUT
		} else if(currentLocationUri == '/one-page-checkout.asp') {
			$('.one-page-checkout-table-1').css('position','relative').css('width','800px').css('margin','auto'); // change table with to 100% from 600 pixels
		
		// TESTIMONIALS
		} else if(currentLocationUri == '/category-s/91.htm') {
			heroSpotLight();
			setTimeout(heroPieces,1900); // heroPieces -> loadFeaturedVideo -> done
		}
		
		
		
		// Run scripts that occur on EVERY page
		loadPage();
		
		/**********************************/
		/* scripts loaded after doc ready */
		/**********************************/
		
		$('.closeButton').click( // close Button 
			function() {
				$(this).parent().animate( { height: 0, marginTop: -30 }, 500);
			}
		);
		
	
	}
);


//////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////// LOAD PAGE /////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////

/*
 * loadPage()
 */
function loadPage() {
	
	// Animate Sides
	initPulsing();
	removeUglyCartText();
	footerLogos();
	
	// Rewrite e-mails (at) this page
	rewriteEmails();	
	
	// Set the IP addres so the login form works
	$('#ipAddressLoginForm').attr('value',userIp);
	
	// prepend #siteAnnouncement to Body
	$('#siteAnnouncement').prependTo('body').show().append('<img src="/v/vspfiles/templates/Black_2010/img/buttons/close.png" class="closeButton" />').animate( { top: 0 }, 1000);
	
}


/*
* rewrite emails
*/
function rewriteEmails() {
	var rewrite = $('.email');
    rewrite.each(function(e) {
		var rewriteText = $(this).text();
		var pieces = rewriteText.split('(at)');
		var theEmail = pieces[0] + "@" + pieces[1];
		$(this).html("<a class='redLink' href='mailto:" + theEmail + "'>" + theEmail + "</a>");
	});
}



/*
* init sidebar pulsing for some browsers
*/
function initPulsing() {

	if(!ie) {
		pulseLeft();
		setInterval('pulseLeft()', 3500);
		pulseRight();
		setInterval('pulseRight()', 3500);
	} else {
		// Hide the Glowing Side Bars
		var side1 = $('#side1');
		var side2 = $('#side2');
		side1.hide().remove();
		side2.hide().remove(); 
	}
}


/*
* hover effect for footer logos
*/
function footerLogos() {
	
	var logos = jQuery('a.footerLogo');
	
	logos.hover(
	
		function() {
			
			
			logos.not(jQuery(this)).stop().animate( { opacity:0.5 }, 400 );
			
		},
		function() {
			
			logos.stop().animate( { opacity:1.0 }, 1000 );
		}
		
		
	);

}


/*
 * black Background
 */
function blackBackground() {
	var contentArea = $('#content_area');
	contentArea.css('background-color','black');
}


/*
 * remove the ugly cart text
 */
function removeUglyCartText() {
	
	var uglyCartTextDiv = $('.cartsummary_full');
	var uglyCartText = uglyCartTextDiv.text();
	
	if(uglyCartText != null) {
		uglyCartText = uglyCartText.replace("items", "");
		uglyCartText = uglyCartText.replace(")", "");
		uglyCartText = uglyCartText.replace("View My Cart", "");
		uglyCartText = uglyCartText.replace("(Your shopping cart contains ", "Items: ");
		uglyCartText = uglyCartText.replace("for a total cost of ", "<br />Total: ");
		uglyCartTextDiv.html(uglyCartText);
		uglyCartTextDiv.show();
	}	
}


function pulseLeft() {
	$('#side1').animate( {opacity: 0.5}, 1500, 
		function() {
			$('#side1').animate( {opacity: 1}, 1000);
		}
	);
}

function pulseRight() {
	$('#side2').animate( {opacity: 0.5}, 1500, 
		function() {
			$('#side2').animate( {opacity: 1}, 1000);
		}
	);
}


/*
*	Only runs on homepage
*/
function changeBgColor() {
	var contentArea = $('#content_area');
	contentArea.css('background','#444444');
}


/*
* loginPageLayout
*/
function loginPageLayout() {
	
	var leftTD, rightTD;
	
	$('b').each( function() {
		if( $(this).text() == 'Returning Customers') {
			leftTD = $(this).parent().parent();
		} else if( $(this).text() == 'New Customers') {
			rightTD = $(this).parent().parent();
		}
	});
	
	leftTD.css('padding','20px').children('font:first').css({
		background	:	'gainsboro',
		display		:	'block',
		fontSize	:	'16px',
		padding		:	'10px'
	});
	leftTD.find('input').css('margin','15px 0px 10px 0px');
	
	
	rightTD.css('padding','20px').children('font:first').css({
		background	:	'gainsboro',
		display		:	'block',
		fontSize	:	'16px',
		padding		:	'10px'
	});
	rightTD.find('input').css('margin','15px 0px 10px 0px');
	
}

/*
* myAccountPageLayout
*/
function myAccountPageLayout() {
	$('#content_area').find('b:not(:first)').each( function() {
		$(this).css({
			display		:	'block',
			fontSize	:	'14px',
			padding		:	'5px'
		});
	});
	
	$('#content_area').find('span').each( function() {
		$(this).css({
			display		:	'block',
			fontSize	:	'12px',
			padding		:	'5px'
		});
	});
}


//////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////// JCAROUSEL /////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////

/**
 * jCarousel item properties
 */
var mycarousel_itemList = [
    {url: "/v/vspfiles/templates/Black_2010/img/jcarousel/slide1.png", title: "", link: "/product-p/pocket_jib.htm"},
    {url: "/v/vspfiles/templates/Black_2010/img/jcarousel/slide2.png", title: "", link: "/product-p/100041.htm"},
    {url: "/v/vspfiles/templates/Black_2010/img/jcarousel/slide3.png", title: "", link: "/product-p/100143.htm"},
    {url: "/v/vspfiles/templates/Black_2010/img/jcarousel/slide4.png", title: "", link: "/category-s/34.htm"},
    {url: "/v/vspfiles/templates/Black_2010/img/jcarousel/slide5.png", title: "", link: "/product-p/100150.htm"},
];


/**
 * setup jCarousel
 */
function setupJcarousel()
{
	$('#mycarousel').jcarousel({
		size: mycarousel_itemList.length,
		itemLoadCallback: {onBeforeAnimation: mycarousel_itemLoadCallback}
	});
}


/**
 * jCarousel load callback
 */
function mycarousel_itemLoadCallback(carousel, state)
{
    for (var i = carousel.first; i <= carousel.last; i++) {
        if (carousel.has(i)) {
            continue;
        }

        if (i > mycarousel_itemList.length) {
            break;
        }

        carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[i-1]));
    }
};


/**
 * jCarousel item html creation helper.
 */
function mycarousel_getItemHTML(item)
{
    return '<a href="' + item.link + '"><img src="' + item.url + '" width="148" height="96" alt="' + item.title + '" title="' + item.title + '" /></a>';
};




//////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////// VIDEO HERO ///////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////


////////////////////
// Hero Spotlight //
////////////////////

function heroSpotLight() {

	var heroMenuDiv = jQuery('#hero-spotlight-menu');
	var heroMenuUl = jQuery('#hero-spotlight-menu-ul');
	var heroMenuLi = jQuery('ul#hero-spotlight-menu-ul > li');
	
	/* animate background to 1.0, increase font-size and left margin, then back to normal */
	heroMenuLi.hover(
		
		function() {
			
			heroMenuDiv.stop().animate( {opacity: 1} );
			jQuery(this).stop().animate( {fontSize: 18, marginLeft: 5}, 200 );
		},
		function() {
			
			heroMenuDiv.stop().animate( {opacity: .65} );
			if(heroMenuUl.attr('class') != jQuery(this).attr('id')) {
				jQuery(this).stop().animate( {fontSize: 16, marginLeft: 0}, 350 );
			}
		}
	);

} // end heroSpotLight


/////////////////
// Hero Pieces //
/////////////////

function heroPieces() {

	/* hero-pieces */
	var pieces = jQuery('.hero-piece');
	pieces.animate( {opacity: 0.5 }, 300);
	
	/* hover effect */
	pieces.hover(
		
		function() {
			
			jQuery(this).stop().animate( {opacity: 1}, 300 );		
		},
		function() {
			
			if(jQuery(this).parent().attr('class') != jQuery(this).attr('id')) {
				jQuery(this).stop().animate( {opacity: 0.5}, 300 );
			}
		}
	);
	
	
	/* PIECE CLICK */
	var piece = jQuery('.hero-piece');
	piece.click(
	
		function () {
		
			var videoId = jQuery(this).attr('title');
			
			var theHtml = '<object height="200" width="385"><param name="allowfullscreen" value="true"><param name="allowscriptaccess" value="always"><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + videoId + '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1&autoplay=1"><embed src="http://vimeo.com/moogaloop.swf?clip_id=' + videoId + '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1&autoplay=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" height="200" width="385"></object>';
			
			jQuery('#heroCenter').empty().css('background-image','none').css('background','none').html(theHtml);
			
			/* add class for piece clicks and opacity changes */
			jQuery(this).parent().removeClass().addClass( jQuery(this).attr('id') );
			
			/* reset the other pieces to less opacity */
			piece.stop().animate( {opacity: 0.5}, 300 );
			jQuery(this).stop().animate( {opacity: 1.0}, 300 );

			
		}
	
	);
	
	/* LIST ITEM CLICK */
	var heroMenuUl = jQuery('#hero-spotlight-menu-ul');
	var heroMenuLi = jQuery('#hero-spotlight-menu-ul li');
	
	heroMenuLi.click(
	
		function () {
			
			var videoId = jQuery(this).attr('class');
			
			var theHtml = '<object height="200" width="385"><param name="allowfullscreen" value="true"><param name="allowscriptaccess" value="always"><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + videoId + '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1&autoplay=1"><embed src="http://vimeo.com/moogaloop.swf?clip_id=' + videoId + '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1&autoplay=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" height="200" width="385"></object>';
			
			/* loads the video */
			jQuery('#heroCenter').empty().css('background-image','none').css('background','none').html(theHtml);
			
			/* add class for menu click */
			heroMenuUl.removeClass().addClass( jQuery(this).attr('id') );
			
			/* reset the other list items to normal size */
			jQuery('#hero-spotlight-menu-ul li').stop().animate( {fontSize: 16, marginLeft: 0}, 350 );
			
			jQuery(this).stop().animate( {fontSize: 18, marginLeft: 5}, 350 );
			
		}
	
	);
	
	/* finally we load the first video after all this is ready */
	setTimeout(loadFeaturedVideo,100);
	
}


/////////////////////////
// Load Featured Video //
/////////////////////////

function loadFeaturedVideo() {
	
	var featuredVideo = jQuery('#featuredVideo');
	var videoId = featuredVideo.attr('class');
	
	featuredVideo.stop().animate( {fontSize: 18, marginLeft: 5}, 200 );
			
	var theHtml = '<object height="200" width="385"><param name="allowfullscreen" value="true"><param name="allowscriptaccess" value="always"><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + videoId + '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1"><embed src="http://vimeo.com/moogaloop.swf?clip_id=' + videoId + '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" height="200" width="385"></object>';
	
	// load the actual video into the html
	jQuery('#heroCenter').empty().css('background-image','none').css('background','none').html(theHtml);

	// FLASH THE HERO PIECES - ANIMATE IN AND OUT QUICKLY	
	var speed = 500;
	var timer = setInterval(flashHeroPieces, speed);
	var pieces = jQuery('#hero > .hero-piece');
	var length = pieces.length;
	var index = 0;
	function flashHeroPieces() {

	     pieces.eq(index).animate( { opacity: 1.0}, 400 );
	
	     index++;
		
		// remove timer if
		if (index > length) {
			clearInterval(timer);
			setTimeout(lowerOpacity,500);
		}
		
		// finally, reset opacity for items not shown in player
		function lowerOpacity() {
			jQuery('#hero > .hero-piece:not(:eq(0))').stop().animate( {opacity: 0.5}, 300 );
		}
	}
	
} // end loadFeaturedVideo

	
	

//////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////// UTILITIES ////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////


/**
 * tableClasses()
 */
function tableClasses(thisPageName) {

	// First, remove .asp from var
	var thisPageName = thisPageName.replace(".asp", "");
	thisPageName = thisPageName.replace("?", "-");
	thisPageName = thisPageName.replace("=", "-");
	thisPageName = thisPageName.replace("_", "-");
	
	// alert(thisPageName);
	
	var table = $('table');
	var td = $('td');
	
	table.each( 
	
		function( intIndex ) {
			
			$(this).addClass('' + thisPageName + '-table-' + intIndex);
				
		}
	);
	
	td.each( 
	
		function( intIndex ) {
			
			$(this).addClass('' + thisPageName + '-td-' + intIndex);
				
		}
	);
}


/**
 * moveContent()
 */
function moveContent() {

	var content = $('#content');
	var contentArea = $('#content_area');

	//contentArea.css('width',980);
	//content.prependTo(contentArea);

}


/**
 * thisPageName()
 */
function thisPageName() {

	thisPageName = window.location.href.toLowerCase();

	if (thisPageName.indexOf('_p/') != -1 || thisPageName.indexOf('-p/') != -1) {

		thisPageName = 'productdetails.asp';

	}

	else if (thisPageName.indexOf('_s/') != -1 || thisPageName.indexOf('-s/') != -1) {

		thisPageName = 'searchresults.asp';

	}

	else {

		//thisPageName = thisPageName.substr(thisPageName.lastIndexOf("/") + 1); //.replace(/\?[\s\S]*/, "");
		thisPageName = thisPageName.substr(thisPageName.lastIndexOf("/") + 1).replace(/\?[\s\S]*/, "");
		
		// alert(thisPageName);
		
	}

	return thisPageName;

}


/*
 * scrollPage()
 */
function scrollPage(altPageY) {
	
	if ( $.browser.msie ) {
		$("html").animate({ scrollTop: (altPageY-90)}, 500 );
		
	} else if ( $.browser.mozilla ) {
		$("html").animate({ scrollTop: altPageY}, 500 );
		
	} else {
		$("body").animate({ scrollTop: altPageY}, 500 );
		
	}

}

/*
* removes the add to cart button based on the image src
*/
function removeAddToCartButton() {
	
	// "/v/vspfiles/templates/Black_2010/images/buttons/btn_addtocart_small.gif"
	var button = $('img[src="/v/vspfiles/templates/Black_2010/images/buttons/btn_addtocart_small.gif"]');
	$(button).each(function() { $(this).hide() });
	
}


/*
* removes the product title link based 2 classes. carefully run this function!
*/
function removeProductLink() {
	
	// productnamecolor colors_productname
	var link = $("a.productnamecolor.colors_productname");
	$(link).each(function() { 
		
		var titleText = $(this).text();
		$(this).parent().append("<b>" + titleText + "</b>");
		$(this).remove();
		
	});
	
	// "/v/vspfiles/photos/news-09-20-2010-1.jpg"
	// "/v/vspfiles/templates/Black_2010/images/nophoto.gif"
	// var newspaper = $('img[src="/v/vspfiles/photos/news-09-20-2010-1.jpg"]');
	var newspaper = $('img[src="/v/vspfiles/templates/Black_2010/images/nophoto.gif"]');
	$(newspaper).each(function() { 
	
		$(this).parent().attr('href','javascript:void(0)')
		$(this).attr('src','/v/vspfiles/photos/news-09-20-2010-1.jpg').css('cursor','default'); 
		
	});
	
}


// ----------------------------------------------------------
// A short snippet for detecting versions of IE in JavaScript
// without resorting to user-agent sniffing
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
//     ie === undefined
// If you're in IE (>=5) then you can determine which version:
//     ie === 7; // IE7
// Thus, to detect IE:
//     if (ie) {}
// And to detect the version:
//     ie === 6 // IE6
//     ie > 7 // IE8, IE9 ...
//     ie < 9 // Anything less than IE9
// ----------------------------------------------------------
 
// UPDATE: Now using Live NodeList idea from @jdalton
 
var ie = (function(){
 
    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');
 
    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );
 
    return v > 4 ? v : undef;
 
}());

