function eptaf(thetitle,theurl){
  var thestring = "";
  for (var i = 0; i < theurl.length; i++) {
    if (theurl.charAt(i) == "&") thestring = thestring + "^"
    else thestring = thestring + theurl.charAt(i)
  }
  window.open("http://www.musiciansmart.com/eptaf/eptaf.asp?thetitle=" + thetitle + "&theurl=" + thestring, "eptaf", "scrollbars,resizable=no,width=316");
}
function openbonuspp() {  popupWin = window.open('bonusinfo.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openbonusrp() {  popupWin = window.open('powerpoints.htm', '', 'scrollbars,resizable=yes,width=516')
}
function opengiftwrap() {  popupWin = window.open('http://www.musiciansmart.com/all_sites/giftwrap.htm', '', 'scrollbars,resizable=yes,width=516')
}
function opencurrency() {  popupWin = window.open('currency.htm', '', 'scrollbars,resizable=yes,width=600')
}
function openshipping() {  popupWin = window.open('shipping.htm', '', 'scrollbars,resizable=yes,width=516')
}
function open40day() {  popupWin = window.open('40day.htm', '', 'scrollbars,resizable=yes,width=516')
}
function open90day() {  popupWin = window.open('90day.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openofferpp() {  popupWin = window.open('offerpp.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openofferrp() {  popupWin = window.open('offerrp.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openofferco() {  popupWin = window.open('offercombo.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openprivacypolicy() {  popupWin = window.open('privacypolicy.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openbusinesshours() {  popupWin = window.open('phone-questions.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openeasypaypp() {  popupWin = window.open('ppeasypay.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openeasypayrp() {  popupWin = window.open('rpeasypay.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openeasypayco() {  popupWin = window.open('comboeasypay.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openemailus() { 
var id = "139"
var url = window.location.href;
if (url.indexOf("fer.")>-1) id = "99";
else if (url.indexOf("unt.")>-1) id = "119";
 popupWin = window.open('http://www.musiciansmart.com/summit/emailus'+id+'.asp', '', 'scrollbars,resizable=yes,width=516')
}

function opensecurity() {  
var id = "139"
var url = window.location.href;
if (url.indexOf("fer.")>-1) id = "99";
else if (url.indexOf("unt.")>-1) id = "119";
popupWin = window.open('https://www.musiciansmart.com/store/security'+id+'.htm', '', 'scrollbars,resizable=yes,width=516')
}
function opencontactus() {  popupWin = window.open('phone-questions.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openwesternunion() {  popupWin = window.open('westernunion.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openfax() {  popupWin = window.open('fax.htm', '', 'scrollbars,resizable=yes,width=516')
}
function opencheck() {  popupWin = window.open('check.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openmoneyorder() {  popupWin = window.open('money-order.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openmail() {  popupWin = window.open('mail-order.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openspanish() {  popupWin = window.open('spanish.htm', '', 'scrollbars,resizable=yes,width=516')
}
function opencreditcards() {  popupWin = window.open('credit-cards.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openanswers() {  popupWin = window.open('answers.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openquiz() {  popupWin = window.open('ear-training-quiz.htm', '', 'scrollbars,resizable=yes,width=516')
}
function openaffiliate() {  popupWin = window.open('affiliate-info.htm', '', 'scrollbars,resizable=yes,width=516')
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i>a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i>d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

$(document).ready(function() {
	var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );
	var is_safari = /safari/.test( navigator.userAgent.toLowerCase() );
	if (is_chrome){
		$("#sound-not-working").remove();
	}
	//this func untested!!!:
	function positionWithin(jqSelector, jqTarget, x, y){
		var offset = jqSelector.offset();
		jqTarget.style( "left: " + (offset.left+x) + ", top: " + (offset.top+y) );
	}
	//$('#btnDebug').click(function(){ //doesn't work since btnFade is created after DOM, so use:
	$("body").delegate("#btnDebug","click",function(){ //delegate includes FUTURE DOM elements 
		$('#debug').html("") //clear the debugging box
	    //$('#courseDiv').delay(300).fadeToggle(400);
		//alert($(this).html())
	});
	//	DEBUGGER DIV add this child to body tag: (comment out when not debugging)
	//$('body').append("<div id='showbox'><input type='button' id='btnDebug' value='click me'><div id='debug'></div></div>")

	// 3 tab openers called from top of page:
	$("#saveTodayTab1").click(function(e){
		changeTab("Perfect");
		e.preventDefault();
	});
	$("#saveTodayTab2").click(function(e){
		changeTab("Relative");
		e.preventDefault();
	});
	$("#saveTodayTab3").click(function(e){
		changeTab("Both");
		e.preventDefault();
	});	
	// 2 positioners called to slow scroll to orderform box:
	$("#courseDiv").delegate("#orderHereLink1","click",function(e){
		goToByScroll('#orderHere1');
		e.preventDefault();
	});
	$("#courseDiv").delegate("#orderHereLink2","click",function(e){
		goToByScroll('#orderHere2');
		e.preventDefault();
	});
	// called from 3 locations on home.htm
	$("#courseDiv, .menu-section").delegate(".openTabBoth","click",function(e){
	//$('#openTabBoth').click(function(e){
		changeTab("Both");
		e.preventDefault();
	});
	// called from green down arrow area all pages
	$("#viewCourseInfoTxt, #greenDownArrow").click(function(e){
	//$('#openTabBoth').click(function(e){
		goToByScroll('#order-form-div');
	});	
	// next 2 called from course-tab-both.htm
	$("#courseDiv").delegate("#viewFullPPdetails","click",function(e){
	//$('#openTabBoth').click(function(e){
		changeTab("Perfect");
		e.preventDefault();
	});
	$("#courseDiv").delegate("#viewFullRPdetails","click",function(e){
	//$('#openTabBoth').click(function(e){
		changeTab("Relative");
		e.preventDefault();
	});	

/* NOTE: worked on elements not load()ed 
this section moved to after load() since delegate only works on events that bubble:
	//balloon selectors:
	//$("[id$='.balloon']") select all elements with an id attribute that ends with "balloon".
	//$("body").delegate("[id$='.balloon']","click",function(){ //delegate includes FUTURE DOM elements 
	function attachBalloons() {
	$("body").delegate("#junk","mouseenter",function(){ //delegate includes FUTURE DOM elements 
		alert("hovering")
		$('#debug').append("hovering") //clear the debugging box
	    //$('#courseDiv').delay(300).fadeToggle(400);
		//alert($(this).html())
	});
	};
*/
	function goToByScroll(id,milliseconds){
		if (milliseconds==null) milliseconds = 400;
		$('body').css({cursor: 'none'});
		$('html,body').animate({scrollTop: $(id).offset().top},milliseconds,"linear", function(){
			$('body').css({cursor: 'default'});
		});
	}

	function changeTab(tab_id, noscroll){
		// ajax in new tab content if not loaded indicated by "Loading...":
		// NOTE: all background tabs are now loaded in myBodyOnload(), but keep this for insurance
		//if ($('#bodyDiv'+tab_id).html() == "Loading..."  ){
		//	$('#bodyDiv'+tab_id).load('course-tab-'+tab_id+'.htm');
		//}
		// hide old and unhide new tab and content:
		if (tab_id != lastHovered) {
			//$('#debug').append("fadedOUT tab:" + lastHovered +"<br>")
			$('#tabDiv'+lastHovered).animate({opacity:0.0});
			$('#bodyDiv'+lastHovered).fadeToggle()
			//$('#debug').append("fadein NEW tab:" + tab_id+"<br>")
			$('#tabDiv'+tab_id).animate({opacity:1.0});	//.animate({opacity: "1.0"}, 1400);
			$('#bodyDiv'+tab_id).fadeToggle()
		}
		if (!noscroll) goToByScroll('#order-form-div');
		lastHovered = tab_id
		//$('#debug').append("changeTab:lastHovered="+lastHovered+"]<br>")
		//$('#debug').append($('#mainTabPic').attr("src")+"<br>")
		currentTab = lastHovered // set global var for hash sign replacement on location.replace
	}
	// replace window history with hash+lastHovered so back history goes to last open tab:
	window.onbeforeunload = function () {
		//alert(window.location);
		// ignored by chrome, documented bug 
		// so handle below for chrome:
		window.location.replace("#"+lastHovered);
		// doesn't work: if (is_chrome)	window.location.href = window.location.href + "#" + window.location.hash 
		if (is_chrome)	{
			// bug in chrome: window.location.replace dosen't work, so use HTML5 spec: 
			// (in conjunction with the onhover change of the hash above ) 
			// see: http://dev.w3.org/html5/spec-author-view/history.html
			// save hover state in object (we're currently ignoring but use in future) 
			var stateObj = { tab: lastHovered };
			history.replaceState(stateObj);
		}
		//$(location).replace($(location).attr('url')+"#"+lastHovered);
		//alert(window.location);
		//return "This session is expired and the history altered.";
	}

	// initialize selected tab (make visible)
	var currentPage = $(location).attr('pathname');
	var hash = $(location).attr('hash');
	var relativePages = ["relativepitch","41powerlessons","coursecontent","rpsuccess"];
	var lastHovered = "Perfect";
	//$('#debug').append('pathname=['+currentPage+"]<br>")
	for (i in relativePages) {
		if (currentPage.indexOf(relativePages[i]) >-1) lastHovered = "Relative";
	}
	if (currentPage.indexOf("perfectrelative") >-1) {lastHovered = "Both";
		//$('#debug').append('pathname=['+currentPage+"tabby<br>")
	}
	//override the above if hash contains exact valid value:
	if (hash == "#Perfect" || hash == "#Relative" || hash == "#Both") lastHovered = hash.substr(1);
	$('#tabDiv'+lastHovered).css({opacity:1.0});
	$('#bodyDiv'+lastHovered).removeClass("hideBody")
	changeTab(lastHovered,true)
	//$('#debug').append("STARTING Tab="+selectedTab+"]<br>")
	//$('#debug').append("lastHovered="+lastHovered+"]<br>")

	// Check if map exists
	if($('#MapTabs')) {
		// Loop through each AREA in the imagemap
		$('#MapTabs area').each(function() {
			// Assign an action to the mouseover event
			$(this).mouseover(function(e) {
				var tab_id = $(this).attr('id').replace("area","")
				//$('#debug').append('on='+tab_id+"<br>")
				changeTab(tab_id, true)
				if (is_safari) window.location.replace("#"+lastHovered);
				if (is_chrome) window.location.hash = lastHovered;
			});
			// Assign an action to the click event
			$(this).click(function(e) {
				///////// May want to clear queue here since 
				///////// changeTab() will repaint proper screen
				e.preventDefault();
				var tab_id = $(this).attr('id').replace("area","");
				//if (selectedTab != tab_id) {
					//alert('You clicked ' + tab_id);
					changeTab(tab_id);
					//window.location.replace("#"+lastHovered);
					//window.location.hash = lastHovered;
				//}
			});
		
		});
	}
	
if ($("#jquery-jplayer1").length) { //exists
	$("#jquery-jplayer1").jPlayer({
		ready: function () {
			this.element.jPlayer("setFile", "c-sharp.mp3", "c-sharp.ogg");
		},
		oggSupport: true,
		customCssIds: true
	})
	.jPlayer("cssId", "pause", "jplayer-pause1")
	.jPlayer("cssId", "play", "jplayer-play1")
	$("#jplayer-play1").click( function () {
			pausePlayer2(); pausePlayer3(); pausePlayer4(); pausePlayer5();
  } );
	function pausePlayer1(e) {
		$("#jquery-jplayer1").jPlayer("pause");
	}

	$("#jquery-jplayer2").jPlayer({
		ready: function () {
			this.element.jPlayer("setFile", "f-minor-9.mp3", "f-minor-9.ogg");
		},
		oggSupport: true,
		customCssIds: true
	})
	.jPlayer("cssId", "pause", "jplayer-pause2")
	.jPlayer("cssId", "play", "jplayer-play2")
	$("#jplayer-play2").click( function () {
			pausePlayer1(); pausePlayer3(); pausePlayer4(); pausePlayer5();
  } );
	function pausePlayer2(e) {
		$("#jquery-jplayer2").jPlayer("pause");
	}

	$("#jquery-jplayer3").jPlayer({
		ready: function () {
			this.element.jPlayer("setFile", "song-example-short.mp3", "song-example-short.ogg");
		},
		oggSupport: true,
		customCssIds: true
	})
	.jPlayer("cssId", "pause", "jplayer-pause3")
	.jPlayer("cssId", "play", "jplayer-play3")
	$("#jplayer-play3").click( function () {
			pausePlayer1(); pausePlayer2(); pausePlayer4(); pausePlayer5();
  } );
	function pausePlayer3(e) {
		$("#jquery-jplayer3").jPlayer("pause");
	}

	$("#jquery-jplayer4").jPlayer({
		ready: function () {
			this.element.jPlayer("setFile", "piano-example-short.mp3", "piano-example-short.ogg");
		},
		oggSupport: true,
		customCssIds: true
	})
	.jPlayer("cssId", "pause", "jplayer-pause4")
	.jPlayer("cssId", "play", "jplayer-play4")
	$("#jplayer-play4").click( function () {
			pausePlayer1(); pausePlayer2(); pausePlayer3(); pausePlayer5();
  } );
	function pausePlayer4(e) {
		$("#jquery-jplayer4").jPlayer("pause");
	}

	$("#jquery-jplayer5").jPlayer({
		ready: function () {
			this.element.jPlayer("setFile", "b-flat.mp3", "b-flat.ogg");
		},
		oggSupport: true,
		customCssIds: true
	})
	.jPlayer("cssId", "pause", "jplayer-pause5")
	.jPlayer("cssId", "play", "jplayer-play5")
	$("#jplayer-play5").click( function () {
			pausePlayer1(); pausePlayer2(); pausePlayer3(); pausePlayer4();
  } );
	function pausePlayer5(e) {
		$("#jquery-jplayer5").jPlayer("pause");
	}
} //if jplayer

});
/*
function slideSwitch() {
    var $active = $('#courseDiv DIV.active');

    if ( $active.length == 0 ) $active = $('#courseDiv DIV:last');

    var $next =  $active.next().length ? $active.next()
        : $('#courseDiv DIV:first');

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

$(function() {
    setInterval( "slideSwitch()", 4000 );
});

*/

var images = new Array()
function preloadImages() {
	for (i = 0; i < preload.arguments.length; i++) {
		images[i] = new Image()
		images[i].src = preload.arguments[i]
	}
}


function myBodyOnload(){

	var images = new Array()
	function preloadImages() {
		for (i = 0; i < preloadImages.arguments.length; i++) {
			images[i] = new Image()
			images[i].src = preloadImages.arguments[i]
		}
	}

//MM_preloadImages('masthead-shoppingcart-o-ear-training.gif',
preloadImages('masthead-shoppingcart-o-ear-training.gif',
'masthead-contactus-o.gif',
'masthead-aboutus-o-ear-training.gif',
'arrow-down-white-ear-training.gif',
'page-2-ear-training-light.gif',
'page-3-ear-training-light.gif',
'page-4-ear-training-light.gif',
'page-5-ear-training-light.gif',
'page-6-ear-training-light.gif',
'arrow-right-green-ear-training.gif',
'arrow-down-green-ear-training.gif',
'nextpage-greenongrey.gif',
'nextpage-greenonblack.gif',
'view-shopping-cart-o.gif',
'shopping-cart-o-ear-training.gif',
'checkmark-bigo-ear-training.gif',
'giftwrapgreen-ear-training.gif',
'giftwrapblue-ear-training.gif',
'order-here-balloon1.gif',
'order-here-balloon2.gif',
'order-here-balloon3.gif',
'order-here-balloonFlip1.gif',
'order-here-balloonFlip2.gif',
'order-here-balloonFlip3.gif'
)

// function runs once for each tab load: 
function attachBalloons(incrementBy) {	
	// set style for picture exceptions: (select the sub hot spot within large img):
	// note: needs background in order to exist for rollover
	tabLoadState += incrementBy
	//execute main body only when all tabs are loaded (==6) 
	if (tabLoadState < 6) return;
	else {
	//we need a delay til all content fully loaded since balloons are positional:
	setTimeout( function() {

	//$("#courseDiv").delegate("#PP1OrderBalloon, #RP1OrderBalloon"),"mouseeenter", function(e){
	$("#PP1OrderBalloon, #RP1OrderBalloon").css({
		"left": "37px",
		"display": "inline",
		"top": "6px",
		"width": "180px",
		"height": "36px",
		"z-index": "1",
		"background": "black",
		"opacity": ".0"
	})

	// create and hide the balloon div:
	$("body").append("<div id='balloon'><img src='order-here-balloon1.gif' width='196' height='120' /></div>");
	// adjust popup's distance from the upper left of rolled over: 
	xOffset = -16; //arrow is right of far left
	yOffset = 0;
	$("#balloon").css({
		"position":"absolute",
		"display":"none",
		"opacity":"1.0"
	})


	$("[id$='Balloon']").mouseenter(function(e){
	//$("#courseDiv").delegate("[id$='Balloon']","mouseeenter", function(e){
		var scrollTop = $(window).scrollTop();
		// use this when relative to the containing element
		//$("#parent_container").innerWidth() - $("#whatever").offset().left + $("#whatever").outerWidth() 
		//find top right corner of hot spot:
		// select the balloon image dynamically (size is assumed to be same, so no change):
		if ($(this).attr("id").indexOf("PPRP") >-1){$("#balloon img").attr("src", "order-here-balloon3.gif")}
		else if ($(this).attr("id").indexOf("RP") >-1){$("#balloon img").attr("src", "order-here-balloon2.gif")}
		else {$("#balloon img").attr("src", "order-here-balloon1.gif")}

		var hotSpotRight = $(this).offset().left + $(this).innerWidth()
		var hotSpotTop = $(this).offset().top
		// position bottom left corner of balloon above and to right of hot spot:
		var balloonTop = hotSpotTop - yOffset - $("#balloon").outerHeight()
		var balloonLeft = hotSpotRight + xOffset
		//re-adjust top and use alternate image if top bleeds offscreen:
		if (balloonTop<scrollTop) {
			balloonTop = $(this).offset().top + $(this).outerHeight()
			$("#balloon img").attr("src", $("#balloon img").attr("src").replace("balloon", "balloonFlip") )
		}
		$("#balloon")
			.css("top",(balloonTop) + "px")
			.css("left",(balloonLeft) + "px")
			.stop(true, true) 
			.fadeToggle("fast");
		
		//$('#debug').append(this.tagName+"<br>");
		//$('#debug').append($(this).offset().top+" :top<br>");
		//$('#debug').append($(this).offset().left+" :left<br>");
		//$('#debug').append($(this).css("width")+$(this).offset().left+ " :right<br>");
	});
	$("[id$='Balloon']").mouseleave(function(){
	//$("#courseDiv").delegate("[id$='Balloon']","mouseleave", function(e){
		$("#balloon").stop(true, true).fadeToggle("fast");
		//$('#debug').append("UNhovering<br>");
	});

 	   }, 3000);//end setTimeout() 
	} // end else (tabLoadState is equal to 6) 
}
/*
*/
//ajax missing tab content in background tabs:
var tabLoadState = 0 // = 6 when complete
	$('#bodyDivPerfect').load('course-tab-perfect.htm #ajaxLoadPerfect',
	attachBalloons(1));

	$('#bodyDivRelative').load('course-tab-relative.htm #ajaxLoadRelative',
	attachBalloons(2));

	$('#bodyDivBoth').load('course-tab-both.htm #ajaxLoadBoth',
	attachBalloons(3)); //note: attachBalloons loads balloons after last tab loaded 

} //end myBodyOnload()


