/* START jQUERY */

$(document).ready(function(){    
	        
	//SHOW/HIDE Sidebar login form
	$(".member-info .login-link").click(function(){
		$(".member-info .login-form").slideDown();
		return false;
	}); 	
	$(".member-info .close-login-form").click(function(){
		$(".member-info .login-form").slideUp();
		return false;
	});  
	// MAKE SURE LOGIN FORM ISN'T BLANK UPON SUBMIT
	$("#loginform").submit(function(){
		//alert("login submitted");
		var uname = $("#user_login").val();
		var pword = $("#user_pass").val();  
		if ((uname == "") || (pword == "")){
			$("#loginformerror").show();
			return false;                       
		}
	})
	
	
	//on page load of any lesson-detail page
	if ($(".lesson-details").length>0){

		// Current Page Reference
		// copyright Stephen Chapman, 1st Jan 2005
		// you may copy this function but please keep the copyright notice with it
		function getURL(uri) {
			uri.dir = location.href.substring(0, location.href.lastIndexOf('\/'));
			uri.dom = uri.dir; if (uri.dom.substr(0,7) == 'http:\/\/') uri.dom = uri.dom.substr(7);
			uri.path = ''; var pos = uri.dom.indexOf('\/'); if (pos > -1) {uri.path = uri.dom.substr(pos+1); uri.dom = uri.dom.substr(0,pos);}
			uri.page = location.href.substring(uri.dir.length+1, location.href.length+1);
			pos = uri.page.indexOf('?');if (pos > -1) {uri.page = uri.page.substring(0, pos);}
			pos = uri.page.indexOf('#');if (pos > -1) {uri.page = uri.page.substring(0, pos);}
			uri.ext = ''; pos = uri.page.indexOf('.');if (pos > -1) {uri.ext =uri.page.substring(pos+1); uri.page = uri.page.substr(0,pos);}
			uri.file = uri.page;
			if (uri.ext != '') uri.file += '.' + uri.ext;
			if (uri.file == '') uri.page = 'index';
			uri.args = location.search.substr(1).split("?");
			return uri;
		}    

		var uri = new Object();
		getURL(uri);
		var path = "/" + uri.path;

	
		//getLessonJson(path,1);      
	} 
	// $('a.play-lesson-video').click(function(){
	// 	alert('foo');
	// 	return false;
	// 
	// });   
	
	// launch note learner
	$('a.note-learner').click(function(){
		window.open($(this).attr('href'),'note-learner','width=640,height=400');
		return false;
	});


	/* NAV LOCAL DROPDOWN HOVER/CLICK */
	$(".nav-local-dropdown").hover(
		function () {
			$(this).addClass("nav-local-dropdown-open");
		}, 
		function () {      
			$(this).removeClass("nav-local-dropdown-open");     
		}     
	);                                      
	
	/* LESSON LEVEL SELECTOR */
	$(".nav-level a").click(function(){  
		$(".nav-level a").removeClass("on"); // turn off all nav level links
		$(this).addClass("on"); // turn on active nav level link
		$(".has-level").children(":not(.level-all)").hide(); // hide contents of the has-level container            
		var activeLevel = $(this).attr("href").split("#")[1];   
		$(".has-level").children().each(function(){ 
			if ($(this).hasClass(activeLevel)) {
				$(this).show();
			}
		});   
		$("#meta-lesson-level").html(activeLevel.split("-")[1]);

			
		var vidToShow = getLessonJson(path,activeLevel.replace("level-",""));
		//alert("video:" + vidToShow);
		////alert("p" + $(player).html());
		return false;
	}) 
	
	/* MAILING LIST > CUSTOMIZE SUBSCRIBE2 INTERFACE */ 
	if ($("body.mailing-list").length>0){  
		$(".copy form").addClass("clearfix");
		$(".copy form p").addClass("clearfix");
		$("input[name='email']").addClass("txt"); 
		$("input[name='email']").attr("maxlength","50");   
		$("input[name='email']").attr("value","");    
		$("input[name='email']").removeAttr("onfocus","");         
		$("input[name='email']").removeAttr("onblur","");            
		$("input[name='subscribe']").addClass("btn-primary");   
		$("input[name='unsubscribe']").addClass("btn-secondary"); 
		// on subscribe and unsubscribe, SUBSCRIBE2 outputs the same message:
		// "To manage your subscription options please login."
		// Let's output something else for now... look for an occurance of "login"
		var message = $(".copy p").html();
		if (message.indexOf("login")>0) {
			$(".copy p").html("Thanks for your interest in iRocku!") 
		}
	}          
	
	/* VIDEO COMMMENT BUTTON STYLING */
	$("#kaltura_video_comment").addClass("btn-secondary");     
	
	/* CONTACT FORM */ 
	$("input[name='pre-register-me']").removeAttr("onclick");  
	
	/* LESSONS > READ MORE */
	$(".read-more").click(function(){
		$(".read-more").parent().siblings(".more-text").slideDown();
		return false;
	})  
	$(".hide-text").click(function(){
		$(".more-text").slideUp();
		return false;
	})                        
	
	/* SPECIAL EVENTS SIDEBAR:  DATE FORMAT */
	if ($(".special-events .date").length>0){
		$(".special-events .date").each(function(){
			var theDate = $(this).html();      
			var theYear = theDate.substring(theDate.length-4,theDate.length);  
			theDate = theDate.substring(0,theDate.length-4);                
			$(this).html("<small>"+theDate+"</small>"+theYear)
		});
	}
	
	/* ZEBRA ROWS */
	$(".zebra tr:even").addClass("alt"); 
	
	/* GLOBAL NAV ON STATES */
	$("#nav-global li[class*='current_page_item'] a").addClass("on");   
	$("#nav-global li[class*='current_page_ancestor'] a").addClass("on");         
	/* UTILITY NAV ON STATES */
	$("#nav-utility li[class*='current_page_item'] a").addClass("on");     
	$("#nav-utility li[class*='current_page_ancestor'] a").addClass("on");   
	
	// BEGIN ACCORDIONS
	
	// 1.A. FAQ ACCORDIAN > for use with a div.faqs container
	var animSpeed = 300;
	var onClass = "on";
	$("h2.faq-header").click(function(){
		if ($(this).hasClass(onClass)){
			$(this).next().slideUp(animSpeed);
			$("h2.faq-header").removeClass(onClass);
		} else {
			$("dl.faq").slideUp(animSpeed);
			$(this).next().slideDown(animSpeed);
			$("h2.faq-header").removeClass(onClass);
			$(this).addClass(onClass);
		}
	});
	$("dl.faq dt").click(function(){
		if ($(this).hasClass(onClass)){
			$(this).next().slideUp(animSpeed);
			$(this).removeClass(onClass);
			$(this).siblings("dt").removeClass(onClass);
		} else {
			$("dl.faq dd").slideUp(animSpeed);
			$(this).next().slideDown(animSpeed);
			$(this).siblings("dt").removeClass(onClass);
			$(this).addClass(onClass);
		}
	});                                    
	
	// 1.B. FAQ ACCORDION > DEFAULT FIRST SECTION OF FAQ TO OPEN 
	if ($("body.faqs").length>0){
		$(".faq-header:first").addClass("on");       
		$("dl.faq:first").attr("style","display:block;");   
	}        
	
	// 2.A. TOOLS & RESOURCES ACCORDION
	$('.resource-list h2').click(function(){ 
		if ($(this).hasClass(onClass)){
			$(this).next().slideUp(animSpeed);
			$(".resource-list h2").removeClass(onClass);
		} else {
			$(".resource-list ul").slideUp(animSpeed);
			$(this).next().slideDown(animSpeed);
			$(".resource-list h2").removeClass(onClass);
			$(this).addClass(onClass);
		}                                 
	}); 	
	$('.resource-list h3').click(function(){ 
		if ($(this).hasClass(onClass)){
			$(this).next().slideUp(animSpeed);     
			$(".resource-list h3").removeClass(onClass);
		} else {
			$(".resource-list ul ul").slideUp(animSpeed);
			$(this).next().slideDown(animSpeed);            
			$(".resource-list h3").removeClass(onClass);
			$(this).addClass(onClass); 
		}                                 
	}); 	
	$('.resource-list h4').click(function(){ 
		if ($(this).hasClass(onClass)){
			$(this).next().slideUp(animSpeed);     
			$(".resource-list h4").removeClass(onClass);
		} else {
			$(".resource-list ul ul ul").slideUp(animSpeed);
			$(this).next().slideDown(animSpeed);            
			$(".resource-list h4").removeClass(onClass);
			$(this).addClass(onClass); 
		}                                 
	});                                      
	
	// 2.B. FAQ ACCORDION > DEFAULT FIRST SECTION OF FAQ TO OPEN 
	if ($("body.top-tools-resources").length>0){
		$(".resource-list h2:first").addClass("on");       
		$(".resource-list ul:first").attr("style","display:block;");   
	}   
	
	// END ACCORDIONS   
	
	/* INITIALIZE FIELD VALUE RESET (looks for presence of "alt" attribute in the input tag) */
	$("input[alt!='']").focus(function(){
		setValue(this,"onfocus"); 
		return false;
	});
	$("input[alt!='']").blur(function(){
		setValue(this,"onblur"); 
		return false;
	});

 }); 
 
 /* BEGIN SETVALUE
 setValue clear's a text input's value and resets it to the input's alt attribute if the user doesn't enter a value */
function setValue(pEl,pSwitch) {	
	if (pSwitch == "onfocus") {
		if (pEl.value == pEl.alt) {
			pEl.value = "";	
		}
	}
	if (pSwitch == "onblur") {
		if (pEl.value == "") {
			pEl.value = pEl.alt;
		}
	}
}
/* END SETVALUE */

var player=null;
function playerReady(thePlayer) {    
	//alert("player ready")
	player = window.document[thePlayer.id];  
}

// laod new video intom JW player
function playNewVideo1(video_source){ 
	player.sendEvent('STOP');         
	player.sendEvent('LOAD', video_source);  
	player.sendEvent('PLAY',true);  
//	player.sendEvent('PLAY',false);                  
}     
             
function playNewVideo(video_source, durationVar){ 
  var obj = {file: video_source, type: 'video',  duration: durationVar}; 
	jwplayer("videoDiv").load(obj);
	jwplayer("videoDiv").play();
}                  
                     
function getLessonJson(pageURL,level){
	var vidToShow;
	var pageUrlEscaped = escape(pageURL);
	var urlVar='/wp-content/themes/irocku/get-lesson-details-ajax.php?pageUrl=' + pageUrlEscaped + '&level=' + level;

	$.ajax({
		url: urlVar,
		dataType: 'json',
		async: 'false',
		success:function(results) {
			printLessonInfo(results);
		}    
	});      
	
	//alert("getLessonJson, level: " + level);

	//alert("VS:" + vidToShow);
	return vidToShow;
}  
	
function printLessonInfo(results){     
	//alert("player ready?")         
	//alert("player" + player);
	//alert("results:" + results.level);
	//alert("printLessonInfo: " + level);
	var hasRights = results.rights; 
	 
	//alert("groovechart: " + results.groovechart_video);       
	//alert("level: " + results.level);       

	if (hasRights){
		var linkList="";
		linkList += '<h2 id="dl-title">Videos &amp; PDFs</h2>';
		linkList += '<p>You have access to the following downloads.</p>'; 
		
		if(results.groovechart_video != ""){  
			linkList += '<h4>Groove Chart</h4><p>';    
			linkList += '<a href="#" rel="' + results.groovechart_video + '" class="play-groovechart-video" id="a-groovechart-video-play" onclick="playNewVideo(this.rel); location.href=\'#video0\'; return false;">Play video</a> | ';  
			linkList += '<a target="_blank" href="' + results.groovechart_video + '" id="a-groovechart-video">Download video</a><br />';
			linkList += '<a target="_blank" href="' + results.groovechart_pdf + '" id="a-groovechart-pdf">Download PDF</a><br /></p>';  
		}

		linkList += '<h4>Lesson</h4><p>';    
		linkList += '<a href="#" rel="' + results.lesson_video + '" class="play-lesson-video" id="a-lesson-video-play" onclick="playNewVideo(this.rel); location.href=\'#video0\'; return false;">Play video</a> | ';  
		linkList += '<a target="_blank" href="' + results.lesson_video + '" id="a-lesson-video">Download video</a><br />';  
		//linkList += '<a href="' + results.lesson_audio + '" id="a-lesson-audio">Download audio</a><br />';
		linkList += '<a target="_blank" href="' + results.lesson_pdf + '" id="a-lesson-pdf">Download PDF</a><br /></p>';
		linkList += '<h4>Exercise</h4><p>';

		linkList += '<a href="#" rel="' + results.exercise_video + '" class="play-lesson-video" id="a-lesson-video-play" onclick="playNewVideo(this.rel); location.href=\'#video0\'; return false;">Play video</a> | ';  
		linkList += '<a target="_blank" href="' + results.exercise_video + '" id="a-exercise-video">Download video</a><br />';
		//linkList += '<a href="' + results.exercise_audio + '" id="a-exercise-audio">Download audio</a><br />';
		linkList += '<a target="_blank" href="' + results.exercise_pdf + '" id="a-exercise-pdf">Download PDF</a><br /></p>';
		linkList += '<h4>Improvisation</h4><p>';

		linkList += '<a href="#" rel="' + results.improv_video + '" class="play-lesson-video" id="a-lesson-video-play" onclick="playNewVideo(this.rel); location.href=\'#video0\'; return false;">Play video</a> | ';  
		linkList += '<a target="_blank" href="' + results.improv_video + '" id="a-improv-video">Download video</a><br />';
		//linkList += '<a href="' + results.improv_audio + '" id="a-improv-audio">Download audio</a><br />';
		linkList += '<a target="_blank" href="' + results.improv_pdf + '" id="a-improv-pdf">Download PDF</a><br /></p>';  
//		linkList += '<p>If you need help on downloading the video, <a href="/faqs/">click here</a> to find the video FAQ.</p>';    
		linkList += '<p>If you need help on downloading the video, <a href="' + results.site_url + '/faqs/">click here</a> to find the video FAQ.</p>';    


		vidToShow = results.lesson_video; 

		//alert("gonna swap vid " + $(player).html());
		player.sendEvent('STOP');
		player.sendEvent('LOAD', vidToShow);  

		player.sendEvent('PLAY',true);  
		player.sendEvent('PLAY',false);  
		//alert("swapped vid " + $(player).html());
		//alert("VS1:" + vidToShow);                
		//Show first frame: http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v5/15995/jw-embedder-reference-guide                                                                                                                                                                 
		//player.onReady(function() { this.play(); } );
		//player.onPlay(function() { this.pause(); } ); 					
	}else{
		//TODO: 
		purchaseLink = results.purchase_link;

		var linkList="";
		linkList += '<h2 id="dl-title">Purchase</h2>';
		linkList += '<p>You do not currently have access to this lesson.</p>';
		linkList += '<p>To access this lesson, <a href="' + purchaseLink + '" class="btn-primary">Purchase Lesson</a></p>';
//		linkList += '<p>To access all our lessons, <a href="/products-page/subscriptions/" class="btn-primary">purchase a subscription</a></p>';
		linkList += '<p>To access all our lessons, <a href="' + results.site_url + '/products-page/subscriptions/" class="btn-primary">purchase a subscription</a></p>';
		vidToShow = results.teaser_video;       
		 
		player.sendEvent('STOP');
		player.sendEvent('LOAD', vidToShow);  

		player.sendEvent('PLAY',true);  
		player.sendEvent('PLAY',false);                
	}
	$('#lesson-downloads .copy').html(linkList);

}    

function checkEmail(val1, obj2, field) {
  val2 = obj2.value;
//alert(val1 + " == " + val2);
	if (val1 == null && val2 == null) {
	  return;
	}  
	if (field == 1 && val1 != null && (val2 == null || val2 == "")) {
	     obj2.focus();
		 return;
	}
	if (val1 != val2) {
	    alert("Input E-mail must be same as confirm E-mail !!!");
	}
}    

function checkValue(obj) {
    val = obj.value;
	if (val == null || val == "") {
	    var rtn = confirm("This is a required field, please input your data!!!");
		if (rtn == true) {
		   obj.focus();
		}
		return;
	}
} 		
	
