// JavaScript Document
$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});


$(function() {
	//startSoundManager();
	setupExpand();
	setupExpandCatalog();
	setupToggleWholesale();
	setupMyAccountLink();
	openCatalogURL();
	$(window).load(function () {
		$('div#loader').fadeOut();
	});
	
	$("div#loader").ajaxStart(function(){
	   $(this).show();
	 });
	 $("div#loader").ajaxStop(function(){
	   $(this).hide();
	 });
});

//My Account Link
function setupMyAccountLink() {
	$.ajax({
		url: "functions/checklogin.php",
		success: function(data) {
			if (data != 'false') {
				$('span.account').html('<a href="cart.php?mode=acct">My Account</a>');	
			}
		}
	});	
}

//Open Catalog by URL hash tag

function openCatalogURL() {
	if(window.location.hash) {
		var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
		if (hash == "catalog") {
			expandCatalog();
		}
		
	} 
}

//Ajax loader


//Initialize Soundmanaager
/*
soundManager.url = 'js/sm2/';
soundManager.flashVersion = 9; // optional: shiny features (default = 8)
soundManager.useFlashBlock = false; // optionally, enable when you're ready to dive in
soundManager.debugMode = false;
// enable HTML5 audio support, if you're feeling adventurous. iPad/iPhone will always get this.
soundManager.useHTML5Audio = true;
soundManager.consoleOnly = true;
soundManager.onready(function() {
  // Ready to use; soundManager.createSound() etc. can now be called.
  alert('sm loaded');
  getAudioLinks();
});	
*/

function getAudioLinks() {
	//This is probably not the best way to do this, looping through so that only upon click is the sound object both created and played
	//Sound objects should probably be created first, and then the click events should just play them
	$('.audio-sample').each(function() {
		i = 1; //iteration number to be used in sound object ID's
		$(this).click(function(event) { //always make sure to pass in the event
			event.preventDefault();
			   
			//If the list item (parent of anchor element) has the class 'selected', then it means the audio is already playing.
			//So we want to just stop the audio from playing, and remove the 'selected' class, and exit the function
			if ($(this).parent().hasClass("selected")) {
				$(this).parent().toggleClass("selected");
				soundManager.stopAll();
				event.preventDefault();
				return;
			}
			//If the list item doesn't have the class selected, it means that another list item might have it
			//So, we want to remove it because the one we're clicking on is the only one that now needs to 
			//become the element with the 'selected' class
			else {
				$('li.selected').removeClass('selected');	
			}
			
			$(this).parent().addClass("selected");
			soundManager.stopAll();
			targetURL = event.target.toString(); //not sure if this is the 'right' way to do this but it works
			
			soundManager.createSound({
				id: 'track' + i, //here's where the iteration becomes part of the sound object's ID
				url: targetURL
			});
			
			soundManager.play('track' + i,{
				onbufferchange: function() {
					if (this.isBuffering == true) {
						$('li.selected').addClass('buffering');
					}
					else if (this.isBuffering == false) {
						$('li.selected').removeClass('buffering');		
					}
				},
				onfinish: function() {
					$('li.selected').removeClass('selected');		
				}
			});
			i++; //and here's where we increment the iteration number
			
		});					    
	})
}

function setupExpand() {
	$('span.expand').click(function(event) {
		$(this).parent().toggleClass("expanded");
		$(this).toggleClass("collapse");
	});
}

function setupExpandCatalog() {
	$('.expand-catalog, .nav-expand-catalog').click(function(event) {
		event.preventDefault();
		expandCatalog();
	});
	$('li.collapse-catalog').click(function(event) {
		if (window.location.hash == "#catalog") {
			window.location.hash = "";
		}
		$("div#container").slideDown(2000, function() {
			$("div#catalog").fadeOut(1000, function() {
				$('li.collapse-catalog').fadeOut(500, function() {
					$('#footer li.expand-catalog').fadeIn(500);							
				});				    
			});									   
		});
	});
	$('div.selection').not('.selection.selected').click(function() {
		
		
		newSelection = $(this).html();
		oldSelection = $(this).parent('.selections').children('.selection.selected').html();
		
		$(this).html(oldSelection);
		$(this).parent('.selections').children('.selection.selected').html(newSelection);
		
		if (newSelection == 'Calendars') {
			$('#product-items').load('functions/productitems.php?category=calendars');
		}
		else if (newSelection == 'Art') {
			$('#product-items').load('functions/productitems.php?category=art');
		}
		else if (newSelection == 'Songbooks') {
			$('#product-items').load('functions/productitems.php?category=songbooks');
		}
		else if (newSelection == 'Literature') {
			$('#product-items').load('functions/productitems.php?category=literature');
		}
		else if (newSelection == 'Music') {
			$('#product-items').load('functions/productitems.php?category=music');
		}
		else if (newSelection == 'Specials') {
			$('#product-items').load('functions/productitems.php?category=specials');
		}		
	});	
}

function expandCatalog() {
	window.location.hash = "#catalog";
	$("div#container").slideUp(1000, function() {
		$('#product-items').load('functions/productitems.php', function(){
			$("div#catalog").fadeIn(1000, function() {
				$('#footer li.expand-catalog').fadeOut(500, function() {
					$('li.collapse-catalog').fadeIn(500);							
				});				    
			});	
		});									   
	});	
}

function setupToggleWholesale() {
	$('a.toggle-wholesale').click(function(event) {
		event.preventDefault();
		
		$.ajax({
			url: "functions/checkwholesale.php",
			cache: false,
			success: function(data){
				if (data == 'true') {
					toggleWholesale();
				}
				else {
					window.location = "wholesale.php";
				}
			}
		});
		
	});
}

function toggleWholesale() {
	$("div#container").slideUp(1000, function() {
		$('div#catalog').fadeOut(500, function() {
			$('#product-items').load('functions/productitems.php', function(){
				$('div#catalog').toggleClass('wholesale');	
				$('div#catalog').fadeIn(500, function() {
					$('#footer li.expand-catalog').fadeOut(500, function() {
						$('li.collapse-catalog').fadeIn(500);							
					});		
				});
			});
		});
	});
}

/* Slideshow */
function cycleSlidesRight() {
	if ($('.slide.selected').hasClass('last')) {
		$('.slide.selected').fadeOut(500, function() {
			$(this).removeClass('selected');
			$('.slide.first').fadeIn(500, function() {
				$(this).addClass('selected');	
			});	
		});		
	}
	else {
		$('.slide.selected').fadeOut(500, function() {
			$(this).removeClass('selected');
			$(this).next('.slide').fadeIn(500, function() {
				$(this).addClass('selected');	
			});	
		});
	}	
}
function cycleSlidesLeft() {
	if ($('.slide.selected').hasClass('first')) {
		$('.slide.selected').fadeOut(500, function() {
			$(this).removeClass('selected');
			$('.slide.last').fadeIn(500, function() {
				$(this).addClass('selected');	
			});	
		});		
	}
	else {	
		$('.slide.selected').fadeOut(500, function() {
			$(this).removeClass('selected');
			$(this).prev('.slide').fadeIn(500, function() {
				$(this).addClass('selected');	
			});	
		});
	}
}
$(function() {
	var timer = setInterval( "cycleSlidesRight()", 15000 );
	$('.right-control').mousedown(function() {
		$(this).addClass('click');
	});
	$('.right-control').mouseup(function() {
		$(this).removeClass('click');
	});	
	$('.right-control').click(function() { 
		cycleSlidesRight();
	
	});
	$('.left-control').mousedown(function() {
		$(this).addClass('click');
	});
	$('.left-control').mouseup(function() {
		$(this).removeClass('click');
	});	
	$('.left-control').click(function() { 
		cycleSlidesLeft();
	});	
	
	$('div.slides').hover(function() {
		clearInterval(timer);
	}, function() {
		//cycleSlidesRight();
		timer = setInterval( "cycleSlidesRight()", 15000 );
	});
});

/* Home music player */
/*
$(function() { 
	$('div.listen').toggle(function() {
		$(this).addClass('hover', 300);
		$(this).children('span').addClass('hover', 300);
		$(this).children('div.tracks').fadeIn(300);
	}, function() {
		$(this).removeClass('hover');
		$(this).children('span').removeClass('hover');
		$(this).children('div.tracks').hide();
	});
});
*/
/* Home links */

$(function() { 
	$('div.twitter').hover(function() {
		$(this).children('.tweets').fadeIn(300);
	}, function() {
		$(this).children('.tweets').fadeOut(300);
	});
	
	$('div.ratepoint').hover(function() {
		$(this).children('.signup').fadeIn(300);
	}, function() {
		$(this).children('.signup').fadeOut(300);
	});
	
	$('div.facebook').hover(function() {
		$(this).children('.like').fadeIn(300);
	}, function() {
		$(this).children('.like').fadeOut(300);
	});	
});

//Add Wholesale Products
$(function() {
	$('span.add-to-cart').click(function() { 
		addWholesaleProducts();
	});
	
	function addWholesaleProducts() {
		i = 0;
		ii = 0;
		$('input.ws-quantity').each(function() {
			q = $(this).val();
			if (q > 0) {
				i++
			}
		});
		$('input.ws-quantity').each(function() {
			q = $(this).val();
			if (q > 0) {
				id = $(this).attr('rel');
				//console.log(id);
				dataString = "mode=add&id="+id+"&quant="+q;
				//$.xhrPool.abortAll();
				$.ajax({
					type:"POST",
					url:"cart.php",
					data:dataString,
					async:false,
					success:function() {
						ii++;
						//console.log(ii);
						if (ii == i) {
							//console.log('Loop completed. All products should have been added.');
							$('span#mc').load('index.php span.mc-container', function() {
								var r=confirm("Your products have been added to the cart.\n\nClick OK to be forwarded to the contents of your cart\nor click Cancel to stay on this page.");
								if (r==true) {
									window.location = "cart.php";
								}
							});	
						}	
					}
				});
			}
			
		});
	}
});

/*
$(function() {
	
	$('span.add-to-cart').click(function() { 
		addWholesaleProducts();
	});
	
	function addWholesaleProducts() {
		var i = 0;
		
		$('input.ws-quantity').each(function(index,element){
			var q = $(this).val();
			//console.log('Value: ' + q)
			if (q != '' && q != 0) {
				i = i + 1;
			}
		});
		
		//console.log('There are ' + i + ' wholesale products to be processed.')
		
		var completedLoops = 0;
		
		if (i > 0) {
			//console.log('Prepaing to add wholesale products to the cart.')	
			
			$('input.ws-quantity').each(function(index,element){
				var q = $(this).val();
				
				if (q != '' && q != 0) {
					var selectedID = $(this).attr('rel');
					
					var dataSting = 'mode=add&id='+selectedID+'&quant='+q;
					
					$.ajax({  
						type: "POST",  
						url: "cart.php",  
						data: dataSting,  
						success: function(data) {  
							//console.log('Product '+selectedID+' should have been added.');
							
							completedLoops += 1;
							
							if (completedLoops == i) {
								//console.log('Loop completed. All products should have been added.');
								$('span#mc').load('index.php span.mc-container', function() {
									var r=confirm("Your products have been added to the cart.\n\nClick OK to be forwarded to the contents of your cart\nor click Cancel to stay on this page.");
									if (r==true) {
										window.location = "cart.php";
									}
								});	
							}
						}  
					});
				}
			});
		} 
		else {
			//console.log('There are no wholesale products to add to the cart.')	
		}
	}
});
*/
