
jQuery(function() {	

	(function($) {
		$.extend({ dequeue : function(elem, effect) {
			$(elem).dequeue(effect);
		}
	});
	})(jQuery);

	$('.hideEle').remove();

	$('#form').submit( function() {
		check();
		return false;
	});

	$('.catname').hover(
		function () {
			if(!$(this).hasClass('on')) {
				$(this).addClass('go');
			}
		},
		function () {
			if(!$(this).hasClass('on')) {
				$(this).removeClass('go');
			}
		}
	);

	$('.catname').bind('click', function() {
		$('.catname').each(function() {
			$(this).removeClass('on');
			$(this).removeClass('go');
		});
		$(this).addClass('on');

		if(this.id == 'topSellers') {
			if(!$('#topProductBox').is(':visible')) {
				if(isHideStopped) {
					showTopSellers();
				}
			}
			else {
				$('#topProductBox').fadeOut('fast', function() {
					$('#topProductBox').fadeIn('slow');
				});
			}
		}
		else if(this.id == 'staffPick') {
			if(!$('#staffProductBox').is(':visible')) {
				if(isHideStopped) {
					showStaffPick();
				}
			}
			else {
				$('#staffProductBox').fadeOut('fast', function() {
					$('#staffProductBox').fadeIn('slow');
				});
			}
		}
		else if(this.id == 'newReleases') {
			$('.genrename').each(function() {
				$(this).removeClass('active');
			});

			if(!$('#newBox').is(':visible')) {
				if($('#'+presentMainDiv+'Box').is(':visible')) {
					$('#'+presentMainDiv+'Box').slideUp(600, function() {
						$('#newBox').slideDown(600);
					});
				}
				else {
					$('#newBox').slideDown(600);
				}
			}
			else {
				$('#newProductBox').fadeOut('fast', function() {
					$('#newProductBox').fadeIn('slow');
				});
			}
			presentMainDiv = 'new';
		}
		else if(this.id == 'myFavorites') {
			$('.genrename').each(function() {
				$(this).removeClass('active');
			});

			if(!$('#favBox').is(':visible')) {
				if($('#'+presentMainDiv+'Box').is(':visible')) {
					$('#'+presentMainDiv+'Box').slideUp(600, function() {
						$('#favBox').slideDown(600);
					});
				}
				else {
					$('#favBox').slideDown(600);
				}
			}
			else {
				$('#favProductBox').fadeOut('fast', function() {
					$('#favProductBox').fadeIn('slow');
				});
			}
			presentMainDiv = 'fav';
		}
	});

	$('.genrename').bind('click', function() {
		if(!genreAnimStopped) { return false; }
		var id = this.id;
		$('.catname').each(function() {
			if(this.id == "newReleases" || this.id == "myFavorites") {
				$(this).removeClass('on');
			}
		});
		$('.genrename').each(function() {
			$(this).removeClass('active');
		});
		$(this).addClass('active');
		genreAnimStopped = false;
		if($('#'+presentMainDiv+'Box').is(':visible')) {
			$('#'+presentMainDiv+'Box').slideUp(600, function() {
				$('#'+id+'Box').slideDown(600, function() {
//					if(!$('#'+id+'Box').hasClass('done')) {
//						getAlbum(id);
//						$('#'+id+'Box').addClass('done');
//					}
					genreAnimStopped = true;
				});
			});
		}
		else {
			$('#'+id+'Box').slideDown(600, function() {
				genreAnimStopped = true;
			});
		}
		presentMainDiv = id;
	});

	$('#cart').Droppable({
		accept :		'reflected', 
		activeclass:	'activeCart', 
		hoverclass:		'hoverCart',
		tolerance:		'intersect',
		onDrop:			addProductToCart
	});

	$('#hideTop').bind('click', function() {
		if($('#topProductBox').is(':visible')) {
			showStaffPick();
		}
		else {
			showTopSellers();
		}
	});

	$('#hideStaff').bind('click', function() {
		if($('#staffProductBox').is(':visible')) {
			showTopSellers();
		}
		else {
			showStaffPick();
		}
	});


	$('.arrowl').click( function() {
		var id = $(this).parent().attr('id');
		var elm = $('#'+id+'Scroll');
		var no = parseInt(elm.css('left'));
		if(no == 0) { return false; }
		if(no+123 == 0) {
			$(this).css({'background-position': '0 -37px'});
		}
		if((Math.abs(no)+248+123+123) == elm[0].offsetWidth) {
			$(this).next().css({'background-position': '0px 0px'});
		}
		if(isAnimStopped) {
			slideCarousel(elm, '+');
		}
	});

	$('.arrowr').click( function() {
		var id = $(this).parent().attr('id');
		var elm = $('#'+id+'Scroll');
		var no = parseInt(elm.css('left'));
		if((Math.abs(no)+248+123+123) == elm[0].offsetWidth) { return false; }
		if((Math.abs(no)+248+123+123+123) == elm[0].offsetWidth) {
			$(this).css({'background-position': '0px -37px'});
		}
		if(no == 0) {
			$(this).prev().css({'background-position': '0px 0px'});
		}
		if(isAnimStopped) {
			slideCarousel(elm, '-');
		}
	});

	$('.genscrollbtns').click( function() {
		if(isAnimStopped) {
			var no = parseInt($('#genscroll').css('top'));
			if(this.id == 'up') {
				if(no >= 0) { return false; }
				isAnimStopped = false;
				no += 31;
				$('#genscroll').animate({top:no+'px'}, 800, function() {
					isAnimStopped = true;
				});
			}
			else if(this.id == 'down') {
				if(no <= -124) { return false; }
				isAnimStopped = false;
				no -= 31;
				$('#genscroll').animate({top:no+'px'}, 800, function() {
					isAnimStopped = true;
				});
			}
		}
	});

	$('img.reflected').livequery('click', function() {

		if(this.id == 'infoImg') {  return false;  }

		var path = $(this).attr('src');
		genre = path.split('/');

		if(genre.length > 3) {
			genre[1] = genre[5];
		}

		var box = $(this).parent().parent().parent();
		var id = $(this).parent().parent().attr('id');
		id = id.split('_');
		id[1] = id[1].replace(/[a-z]/g, '');

		var price = $(box).find('span.amount').html();

		var desc1 = $(box).find('span.name').html();
		var desc2 = $(box).find('span.hide').html();

		var name = desc1 + ' : ' + desc2;

//		if(!$('#'+genre[1]+'Box').hasClass('done')) {
//			getAlbum(genre[1]);
//			$('#'+genre[1]+'Box').addClass('done');
//		}

		showProdInfo(id[1], genre[1], path, name, price, id[0]);
	});


	$('img.reflected').livequery( function() {
		if($(this).parent().parent().hasClass('product')) {
			$(this).hover(
				function() {
					$(this).parent().parent().parent().prev().children('img').removeClass('hidediv');
					$(this).parent().parent().next().removeClass('hidediv');
				},
				function() {
					$(this).parent().parent().parent().prev().children('img').addClass('hidediv');
					$(this).parent().parent().next().addClass('hidediv');
				}
			);
		}
	});

	$('div.deal').livequery('click', function() {
		var info = $(this).attr('id');
		info = info.split('_');

		$('#'+info[0]+'_prod'+info[1]).find('img.reflected').trigger('click');
	});

	$('#checkout').click( function() {
		checkProducts();
	});

	$('#back1').click( function() {
		$('#lightbox_checkout').fadeOut('normal', function() {
			$('#lightbox-overlay').fadeOut('fast', function() {
				$('#checkoutProducts tbody').html('');
			});
		});
		return false;
	});

	$('#back2').click( function() {
		$('#lightbox_prodInfo').fadeOut('normal', function() {
			$('#lightbox-overlay').fadeOut('fast');
		});
		return false;
	});

	$('#closeInfo').click( function() {
		$('#back2').trigger('click');
	});

	$('#buynow').click( function() {
		var id = $('#infoID').html();
		id = id.split('-');
		var genre = $('#infoG').html().toLowerCase();
		var prodBox = genre + '_prod' + id[1];
		addProductToCart($('#'+prodBox).parent().find('div.product img'));

		$('#lightbox_prodInfo').fadeOut('fast', function() {
			$('#lightbox-overlay').fadeOut('fast');
		});

		return false;
	});

	$('#search').click( function () {
		var txt = $('#searchtext').attr('value');
		$('#searchmsg').html(txt);
		$('#lightbox-overlay').fadeIn('fast', function() {
			$('#lightbox_search').fadeIn('fast', function() {
				txt = txt.replace(/^\s+/,"");
				search(txt);
			});
		});
	});

	$(document).keyup(function(event){
		if (event.keyCode == 27) {
			escClose();
		}
		return false;
	});

	$('#rating1').rating('', {maxvalue:5, curvalue:2});
	$('#rating2').rating('', {maxvalue:5, curvalue:5});

	$('#searchtext').focus( function() {
		$(this).attr({value: ' '});
	});

	$('#searchtext').blur( function() {
		var val = $('#searchtext').attr('value');
		if(val == ' ') {
			$(this).attr({value: 'Search Music'});
		}
	});

	$('#paypal').click(function() {
		window.open('http://paypal.com');
		return false;
	});

	$('#check_css').click(function() {
		window.open('http://jigsaw.w3.org/css-validator/validator?uri=http://sourcebits.com/nerve&profile=css3&usermedium=all&warning=1&lang=en');
		return false;
	});

	$('#check_xhtml').click(function() {
		window.open('http://validator.w3.org/check?uri=http://sourcebits.com/nerve');
		return false;
	});

	$('#contact').click(function() {
		window.open('http://sourcebits.com/contact');
		return false;
	});

});


function check() {
	$('#search').trigger('click');
	return false;
}

var presentMainDiv = 'new';
var isAnimStopped = true;
var isHideStopped = true;
var genreAnimStopped = true;

function slideCarousel(elm, sign) {
	var	currentProductId = 0;
	var no = parseInt(elm.css('left'));
	if(no-123 == 0) {
		currentProductId = 1;
	}
	else {
		currentProductId = (Math.abs(no)/123)+2;
	}

	isAnimStopped = false;
	if(sign == '+') { no += 123; }
	else { no -= 123; }

	elm.animate({left:no}, 600, 'easeInQuad', function() {
		isAnimStopped = true;
	});
}

var addProductToCart = function(dragged) {
	var cartItem;
	var mainBox = $(dragged).parent().parent().parent();
	var productId = $(mainBox).children('div.product').attr('id').split('_');
	var productImg = $(dragged).attr('src');
	
	var priceDiv = $(mainBox).children('div.info').children('div.price_box');
	var productPrice = parseFloat($(priceDiv).find('span.amount').html());

	var descDiv = $(mainBox).children('div.info').children('div.desc_box').children().children().children();
	var productDesc = $(descDiv).html();

	var isInCart = $('#' + productId[1] + '_cart');
	if (isInCart.size() == 1) {
		var quantity = parseInt(isInCart.find('span.quantity').html()) + 1;
		isInCart.find('span.quantity').html(quantity+'');
		cartItem = isInCart.get(0);
	}
	else {
		$('#cartProducts').append('<div class="productCart" id="' + productId[1] + '_cart"><div class="prodcontainer"><div class="sampleImage"><img src="'+ productImg +'" alt="" /></div><div class="desc">'+ productDesc +'$<span class="price">'+ productPrice +'</span>&nbsp;(x <span class="quantity">1</span>)</div></div><div class="prodRemove"></div><div class="clr"></div></div>')
		.find('div.productCart:last')
		.fadeIn(1000)
		.find('div.prodRemove')
		.bind('click', function() {
			$(this.parentNode).fadeOut(1000, function() {
				var node = this;
				$('#cartTotal').parent().animate({color:'#ffff00'}, 'slow', function() {
					$(node).remove();
					var total = calculateCartTotal();
					$('#cartTotal').parent().find('span').html(total).parent().animate({color:'#aeee25'}, 'slow');
				});
			});
			return false;
		});
		cartItem = $('div.productCart:last').get(0);
	}
	var total = calculateCartTotal();
	$('#cartTotal').parent().animate({color:'#ff6600'}, 'slow', function() {
		$(this).find('span').html(total).parent().animate({color:'#aeee25'}, 'slow');
	});
	return cartItem;
};

function calculateCartTotal() {
	var total = 0;
	$('#cartProducts .productCart').each( function() {
			var price = parseFloat($('span.price', this).html());
			var quantity = parseInt($('span.quantity', this).html());
			total += price * quantity;
		}
	);
	total = formatNum(total);
	return total;
}

function formatNum(nr) {
	thousands = parseInt(nr/1000);
	hundreds = parseInt(nr - thousands*1000);
	decimals = parseInt((nr - parseInt(nr)) * 100);
	return (thousands > 0 ? thousands + ' ' : '') + (nr > 1000 & hundreds < 100 ? '0' : '') + (nr > 1000 & hundreds < 10 ? '0' : '') + hundreds + '.' + (decimals > 0 ? decimals : '0');
}

function showTopSellers() {
	if(isHideStopped) {
		isHideStopped = false;
		$('#staffProductBox').children('div.arrowl').fadeOut('fast');
		$('#staffProductBox').children('div.arrowr').fadeOut('fast', function() {
			$('#staffProductBox').slideUp(600, function() {
				$('#topProductBox').slideDown(600, function() {
					$('#topProductBox').children('div.arrowl').fadeIn('fast');
					$('#topProductBox').children('div.arrowr').fadeIn('fast');
					$('#hideTop').removeClass('hide_down').addClass('hide_up');
					$('#hideStaff').removeClass('hide_up').addClass('hide_down');
					isHideStopped = true;
				});
			});
		});
	}
	else {
		return false;
	}
}

function showStaffPick() {
	if(isHideStopped) {
		isHideStopped = false;
		$('#topProductBox').children('div.arrowl').fadeOut('fast');
		$('#topProductBox').children('div.arrowr').fadeOut('fast', function() {
			$('#topProductBox').slideUp(600, function() {
				$('#staffProductBox').slideDown(600, function() {
					$('#staffProductBox').children('div.arrowl').fadeIn('fast');
					$('#staffProductBox').children('div.arrowr').fadeIn('fast');
					$('#hideTop').removeClass('hide_up').addClass('hide_down');
					$('#hideStaff').removeClass('hide_down').addClass('hide_up');
					isHideStopped = true;
				});
			});
		});
	}
	else {
		return false;
	}
}

function checkProducts() {

	$('#checkoutProducts tbody').append('<tr><td class="covercell">&nbsp;</td><td class="namecell">&nbsp;</td><td class="rightalign">Price</td><td class="quantitycell">Quantity</td><td class="rightalign">Total</td><td class="rembtncell">&nbsp;</td></tr>');

	$('#cartProducts .productCart').each( function() {
		var name = $(this).attr('id');
		var path = $('div.sampleImage img', this).attr('src');
		var desc1 = $('span.name', this).html();
		var desc2 = $('span.hide', this).html();
		var price = parseFloat($('span.price', this).html());
		var quantity = parseInt($('span.quantity', this).html());
		var total = formatNum(price * quantity);

		$('#checkoutProducts tbody').append('<tr><td class="covercell"><img src="'+path+'" /></td><td class="namecell">'+desc1+' : '+desc2+'</td><td class="rightalign">$'+price+'</td><td class="quantitycell"><input class="smalltext" name="" type="text" value="'+quantity+'" /></td><td class="rightalign">$'+total+'</td><td class="rembtncell"><div name="'+name+'" class="imagebtn removebtn png"></div></td></tr>')
		.find('div.removebtn')
		.bind('click', function() {
			var pid = $(this).attr('name');
			$(this).parent().parent().fadeOut(1000, function() {
				$('#'+pid).remove();
				$(this).remove();
				calculateCheckoutTotal();
			});
			return false;
		});
	});
	calculateCheckoutTotal();

	$('#lightbox-overlay').fadeIn('fast', function() {
		$('#lightbox_checkout').fadeIn('normal');
	});

}

function calculateCheckoutTotal() {
	var subtotal = 0;
	$('#cartProducts .productCart').each( function() {
		var price = parseFloat($('span.price', this).html());
		var quantity = parseInt($('span.quantity', this).html());
		var total = price * quantity;

		subtotal += total;
	});

	subtotal = formatNum(subtotal);
	$('#subTotal').html(subtotal);
	var tax = formatNum(subtotal*0.05);
	$('#tax').html(tax);
	var total = parseFloat(subtotal) + parseFloat(tax);
	$('#total').html(formatNum(total));
	$('#cartTotal').html(formatNum(total));
}

function showProdInfo(id, genre, path, name, price, cat) {

	if(cat == 'fav') {
		$('#rating1').addClass('hidediv');
		$('#rating2').removeClass('hidediv');
	}
	else {
		$('#rating1').removeClass('hidediv');
		$('#rating2').addClass('hidediv');
	}

	$('#infoImg').attr({src: path});
	genre = genre.toUpperCase();
	$('#infoAA').html(name);
	$('#infoG').html(genre);
	$('#infoY').html('');
	genre = genre.charAt(0);
	$('#infoID').html(genre+'-'+id);
	price = price.replace('$', '');
	$('#infoP').html('$'+price);

	$('#infoImg').reflect({height: 0.6, opacity: 0.6});

	$('#lightbox-overlay').fadeIn('normal', function() {
		$('#lightbox_prodInfo').fadeIn(800);
	});
}

function search(txt) {
	if(presentMainDiv == 'search') {
		if($('#'+presentMainDiv+'Box').is(':visible')) {
			$('#'+presentMainDiv+'Box').slideUp('fast');
		}
	}

	$('#searchProductBoxScroll tbody tr').html('');
	$('#searchProductBoxScroll').attr({style: 'left:0'});
	$('#searchProductBox').find('div.arrowl').removeAttr('style');

	$.getJSON('json/list.json', function(json) {
		searchJSON(json, txt);
		$('#lightbox_search').fadeOut('fast', function() {
			$('#lightbox-overlay').fadeOut('fast', function() {
				if(!genreAnimStopped) { return false; }
				var id = 'search';
				genreAnimStopped = false;
				if($('#'+presentMainDiv+'Box').is(':visible')) {
					$('#'+presentMainDiv+'Box').slideUp(600, function() {
						$('#'+id+'Box').slideDown(600, function() {
							genreAnimStopped = true;
						});
					});
				}
				else {
					$('#'+id+'Box').slideDown(600, function() {
						genreAnimStopped = true;
					});
				}
				presentMainDiv = id;
			});
		});
	});
	return false;
}

function searchJSON(json, str) {
	var genreName;
	var result;
	var checkId = 0;
	var ct = 0;
	str = str.toLowerCase();

	$.each(json.genre, function(k) {
		genreName = k;
		$.each(this, function(l) {
			result = this.artist.toLowerCase().search(str);
			if(result >= 0) {
				createAlbum(this.prodId, genreName, this.artist, this.album, this.price, this.path)
				checkId = this.prodId;
				ct += 1;
			}
			if(checkId != this.prodId) {
				result = this.album.toLowerCase().search(str);
				if(result >= 0) {
					createAlbum(this.prodId, genreName, this.artist, this.album, this.price, this.path)
					ct += 1;
				}
			}
		});
	});

	if(ct == 0 ) {
		var txt = '<td><div class="title2">No Search results found with "'+str+'"</div></td>';
		$('#searchProductBoxScroll tbody tr').append(txt);
	}
	if(ct < 5) {
		$('#searchProductBox').find('div.arrowl').hide();
		$('#searchProductBox').find('div.arrowr').hide();
	}
	else {
		$('#searchProductBox').find('div.arrowl').show();
		$('#searchProductBox').find('div.arrowr').show();
	}
}

function createAlbum(pid, genre, artist, album, price, path) {
	var block = $('#album_template tbody tr').html();
	var path = genre+'/'+path+'.png';
	block = block.replace('n_m', 'search');
	block = block.replace('_album_id', pid);
	block = block.replace('#class_name#', 'reflect');
	block = block.replace('#album_path#', path);
	block = block.replace('#album_price#', price);
	block = block.replace('#album_artist#', artist);
	block = block.replace('#album#', album);
	$(block).appendTo('#searchProductBoxScroll tbody tr');

	$('#search_prod'+pid+' img').reflect({height: 0.3, opacity: 0.6});

	$('#search_prod'+pid+' img').Draggable({ revert: true, ghosting: true, opacity: 0.4 });
}

function escClose() {
	if($('#lightbox_checkout').is(':visible')) {
		$('#lightbox_checkout').fadeOut(800, function() {
			$('#lightbox-overlay').fadeOut('normal', function() {
				$('#checkoutProducts tbody').html('');
			});
		});
	}
	else if ($('#lightbox_prodInfo').is(':visible')) {
		$('#lightbox_prodInfo').fadeOut(800, function() {
			$('#lightbox-overlay').fadeOut('normal');
		});
	}
}


