// default.js
var p 				= 2;
var retrieve 		= false;
var stock_L, stock_R, stock_Y, stock_M;
var bCount			= 0;
var bValid 			= true;

//
$.postJSON = function (url, data, callback) {
	$.post(url, data, callback, 'json');
};

$(function(){
	
	// scroll
	$(window).scroll(function(){
		if(isScrollBottom() && retrieve == false){
			//scroll is at the bottom
			if($('#yakOffDate').val()){
				getAdditionalComments();
			}
		}
	});
	
	function isScrollBottom() {
		var documentHeight = $(document).height();
		var scrollPosition = $(window).height() + $(window).scrollTop();
		return (documentHeight == scrollPosition || documentHeight == scrollPosition - 300);
	} 
	
	
	// clear search input
	$('#keywords').focus(function(){
		if($(this).val() == 'product search'){
			$(this).css({'background':'#eeeeee'}).val('');
		}
	}).blur(function(){
		if($(this).val() == ''){
			$(this).val('product search');
		}
	});
	
	$('#btnY').click(function(){
		if($('#keywords').val() != 'product search' && $('#keywords').val() != '' && $('#keywords').val().length > 2){
			$('#keywords').css({'background':'#ccffcc'});
			window.location = $('#yakProductSearch').attr('action') + 'keywords/' + safeSearchURL($('#keywords')) + '/';
		} else {
			$('#keywords').css({'background':'#ffcccc'});
		}
		
		return false;
	});
	
	if($('#yakOffDate').val()){
		getAdditionalComments();
		$('.postComment').hide();
	}
	
	$('a').livequery(function(){
		if($(this).attr('onclick')	){
			$(this).click(function(){
				return false; 
			});
		}
	});
	
	$('.postForm').ajaxForm({ 
        dataType:  		'json',
		url: '/ajax.php?action=post&command=comments&ajax=y',
		beforeSubmit: 	function(data, jqform, options){
			
			var notValid = false; 
			
			for (var i=0; i < data.length; i++) { 
				if (!data[i].value && data[i].name == 'author') {
					jqform.find('input[name=author]').css({'background':'#ffcccc'});
					notValid = true; 
				} else if(data[i].name == 'author'){
					jqform.find('input[name=author]').css({'background':'#ccffcc'});
				}
				
				if (!regIsEmail(data[i].value) && data[i].name == 'email') { 
					jqform.find('input[name=email]').css({'background':'#ffcccc'});
					notValid = true; 
				} else if(data[i].name == 'email'){
					jqform.find('input[name=email]').css({'background':'#ccffcc'});
				}
				
				if (!regIsUrl(data[i].value) && data[i].value && data[i].name == 'url') { 
					jqform.find('input[name=url]').css({'background':'#ffcccc'});
					notValid = true; 
				} else if(data[i].name == 'email'){
					jqform.find('input[name=url]').css({'background':'#ccffcc'});
				}
				
				if (!data[i].value && data[i].name == 'comment') {
					jqform.find('textarea[name=comment]').css({'background':'#ffcccc'});
					notValid = true; 
				} else if(data[i].name == 'comment'){
					jqform.find('textarea[name=comment]').css({'background':'#ccffcc'});
				}
			}
			
			if(notValid == true){
				return false;	
			}
		},
        success:   		function(data){
			if(data.success == true){
				$('#postComment_' + data.productID).after(data.comments);
				$('#postForm_' + data.productID).find('input, textarea').css({'background':'#ffffff'});
				$('#postForm_' + data.productID).find('textarea').val('');
				$('#postComment_' + data.productID).slideToggle('slow');
			} else {
				
			}
		}
    });
	
	$('.addForm').ajaxForm({ 
        dataType:  		'json',
		url: '/ajax.php?action=post&command=cart&ajax=y',
		beforeSubmit: 	function(data, jqform, options){
			
			var notValid = false; 
			
			for (var i=0; i < data.length; i++) { 
				if (data[i].value && data[i].name == 'side') {
					
					if(data[i].value == 'L'){ notValid = canAdd(stock_L, 'L'); }
					if(data[i].value == 'R'){ notValid = canAdd(stock_R, 'R'); }
					if(data[i].value == 'Y'){ notValid = canAdd(stock_Y, 'Y'); }
					if(data[i].value == 'M'){ notValid = canAdd(stock_M, 'M'); }
					
				}
			}
			
			if(notValid == true){
				return false;	
			} else {
				
			}
		},
        success:   		function(data){
			if(data.success == true){
				$('#mainCart').html(data.html);
				$('html, body').animate({
					scrollTop: 0
				}, 1000, function(){
					$('#mainCart').slideDown('slow');
				});
			} else {
			}
		}
    });
	
	$('#dailyPollForm').livequery(function(){
		$(this).ajaxForm({ 
			dataType:  		'json',
			url: '/ajax.php?action=post&command=vote&ajax=y',
			beforeSubmit: 	function(data, jqform, options){
				
				var notValid = false; 
				
				for (var i=0; i < data.length; i++) { 
					if (!data[i].value && data[i].name == 'dailyPollChoice') {
						notValid = true; 
					}
				}
				
				if(notValid == true){
					return false;	
				}
			},
			success:   		function(data){
				if(data.success == true){
					$('.pollChoices').replaceWith(data.html);
				} else {
					
				}
			}
		});
	});
	
	$('tr.even,tr.odd').livequery(function(){
		$(this).mouseover(function(){ $(this).toggleClass('hover'); }).mouseout(function(){ $(this).toggleClass('hover'); });							   
	});
	
	$('td.date').livequery(function(){
		$(this).mouseover(function(){ $(this).toggleClass('hover'); }).mouseout(function(){ $(this).toggleClass('hover'); });							   
	});
	
	$('body').click(function(){
		if($('#mainCart:visible').html()){
			$('#mainCart').slideUp('slow');
		}
	});
	
	$('#sstate').change(function(){
		stateChange($(this).val());							 
	});
	
	//addthis.button('#blog-post-24', {}, {url: "http://example.com/blog/24", title: "The 24th post"});
	
	checkForHash();
	
});

function checkForHash(){
	if(window.location.hash.substring(1,window.location.hash.length)){
		if(window.location.hash.length > 0){
			
			hashVal 	= window.location.hash.substring(1,window.location.hash.length); 
			hashPieces	= hashVal.split('_');
			
			if(hashPieces[0] && hashPieces[0] == 'open' && hashPieces[1]){ $('#postComment_'+hashPieces[1]).slideDown('slow'); }
			
		}
	}
}

function viewCart(){
	$('#mainCart').slideDown('slow');
}

function deleteProduct(obj, id){
	
	$.getJSON('/ajax.php', {'ajax': 'y', 'action':'delete', 'command':'cart', 'productInventoryID':id }, function(data){
		if(data.success == true){
			$(obj).fadeOut('slow',function(){ 
				$(this).remove();
				if($('#shoppingCart').html()){
					if(data.subtotal > 0){
						$('#subtotal').html('$ ' + data.subtotal);
						$('#shipping').html('$ ' + data.shipping);
						$('#total').html('$ ' + data.total);
					} else {
						$('#shoppingCart').replaceWith('<p>You currently have no items in your shopping cart.</p>');
					}
				} else {
					if(data.subtotal > 0){
						$('#total').html('Total: $' + data.subtotal);
					} else {
						$('#mainCart').find('.cartProducts').html('<p>You currently have no items in your shopping cart.</p>');
						$('#mainCart').find('.cartInfo').remove();
					}
				}
			});
		} else {
			
		}
	});
	
}

function updateQuantity(){

	$('input[name=quantity]').each(function(){
	
		quantity = $(this).val();
		obj		 = $(this).parents('tr');
		id		 = serializeIDOnly(obj);
		
		quantityProduct(obj, id, quantity);
	
	});

}

function quantityProduct(obj, id, quantity){
	
	if(quantity < 1){
		deleteProduct(obj, id);
	} else {
		$.getJSON('/ajax.php', {'ajax': 'y', 'action':'quantity', 'command':'cart', 'productInventoryID':id, 'quantity':quantity }, function(data){
			if(data.success == true){
					if($('#shoppingCart').html()){
						if(data.subtotal > 0){
							$('#subtotal').html('$ ' + data.subtotal);
							$('#shipping').html('$ ' + data.shipping);
							$('#total').html('$ ' + data.total);
							
							$('tr').removeClass('error');
							
							if(data.noCheckout){
								$('#canCheckout').addClass('hide');
								$('#canNotCheckout').removeClass('hide');
								for(x in data.outOfStock){
									$('#'+data.outOfStock[x]).addClass('error');	
								}
							}else{
								$('#canCheckout').removeClass('hide');
								$('#canNotCheckout').addClass('hide');
							}
						} else {
							$('#shoppingCart').replaceWith('<p>You currently have no items in your shopping cart.</p>');
						}
					} else {
						if(data.subtotal > 0){
							$('#total').html('Total: $' + data.subtotal);
						} else {
							$('#mainCart').find('.cartProducts').html('<p>You currently have no items in your shopping cart.</p>');
							$('#mainCart').find('.cartInfo').remove();
						}
					}
			} else {
				
			}
		});
	}
	
}

function stateChange(state){
	
	$.getJSON('/ajax.php', {'ajax': 'y', 'action':'update', 'command':'state', 'state':state }, function(data){
		if(data.success == true){

			$('#subtotal').html('$ ' + data.subtotal);
			$('#shipping').html('$ ' + data.shipping);
			$('#tax').html('$ ' + data.tax);
			$('#total').html('$ ' + data.total);
					
		}
	});
	
}

function yakItemDisplay(obj, section){
	if($('#vs').html()){ $('#vs').css({'z-index': '1'}); }
	
	obj.parents('.yakItem').find('.info>div:not(.' + section + ')').fadeOut();
	obj.parents('.yakItem').find('.info>div.' + section + '').fadeIn();
	obj.siblings('a').removeClass('current');
	obj.addClass('current');
	
	if(section != 'buy'){
		obj.delay(60000, function(){
			if(obj.attr('class') == 'current'){
				obj.removeClass('current');
				obj.parents('.yakItem').find('.info>div:not(.image)').fadeOut();
				obj.parents('.yakItem').find('.info>div.image').fadeIn();
			}
		});
	}
}

function getAdditionalComments(){
	retrieve = true;
	
	var loader = '<div class="ajax-loader"><img src="/images/layout/ajax-loader.gif" /> retrieving additional comments</div>';
			
	$('.comments').append(loader);
	
	$.getJSON('/ajax.php', {'ajax': 'y', 'action':'get', 'command':'comments', 'dates':$('#yakOffDate').val(), 'p':p}, function(data){
		if(data.success == true){
			
			$('#yakItem_' + data.comments.left_id).find('.comments').append(data.comments.left_comments);
			$('#yakItem_' + data.comments.right_id).find('.comments').append(data.comments.right_comments);	
			
			p++;
			
			$('.ajax-loader').replaceWith('');
			
			if(data.comments.left_comments != '' || data.comments.right_comments != ''){
				retrieve = false;
			}
		} else {
		}
	});	
}

function flagComment(commentID){
	$.getJSON('/ajax.php', {'ajax': 'y', 'action':'flag', 'command':'comment', 'productCommentID':commentID}, function(data){
		if(data.success == true){
			$('#comment_' + commentID).find('.flag').fadeOut('slow');
		} else {
			
		}
	});	
	
}

function getMoreTxt(obj){
	obj.parent('.moreBtn').siblings('.moreTxt').show('slow', function(){ $(this).css({'display':'inline'})});
	obj.parent('.moreBtn').hide();	
	return false;
}

function showPostComment(obj){
	obj.siblings('.postComment').slideToggle('slow');
	return false;
}

function getDailyPollChoices(){
	$.getJSON('/ajax.php', {'ajax': 'y', 'action':'get', 'command':'pollChoices'}, function(data){
		if(data.success == true){

			$('.pollResults').replaceWith(data.html);

		} else {
		}
	});	
}

function getDailyPollResults(dates){
	$.getJSON('/ajax.php', {'ajax': 'y', 'action':'get', 'command':'pollResults', 'dates':dates}, function(data){
		if(data.success == true){
			
			if($('.pollChoices').html()){
				$('.pollChoices').replaceWith(data.html);
			} else {
				$('.pollResults').replaceWith(data.html);
			}

		} else {
		}
	});	
}

function useBilling(){
	$('#sfirstName').val($('#firstName').val());
	$('#slastName').val($('#lastName').val());
	
	$('#scompany').val($('#company').val());
	$('#saddress1').val($('#address1').val());
	$('#saddress2').val($('#address2').val());
	$('#scity').val($('#city').val());
	$('#sstate').val($('#state').val());
	$('#szipCode').val($('#zipCode').val());
	
	stateChange($('#state').val());
}

function showCSC(){

	$('#csc').replaceWith('<br />The CSC is usually 3-4 numbers located on the front or back of your credit card similar to the areas highlighted in red below.<br /><img src="/images/layout/cardFront.jpg" />&nbsp;<img src="/images/layout/cardBack.jpg" />');
	
}

function yakLink(obj){
	
	var url = obj.find('a').attr('href');
	
	if(url){
		window.location = url;
		return false;
	}
	
}

function safeSearchURL(objRead){
	var tempString = objRead.val();
	tempString = tempString.toLowerCase().replace(/\s+/g, '-').replace(/[^A-Za-z0-9\- ]+/g, '');

	return tempString;
}

function regIsEmail(fData){
	var reg = new RegExp("^[0-9a-zA-Z_\.]+@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$");
	
	return reg.test(fData);
}

function regIsUrl(fData){
	var reg = new RegExp("/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/");
	
	return reg.test(fData);
}

function updateTips(t) {
	bCount++;
	if(bCount < 2){
		$('#formMsg').text(t).show();
	} else {
		$('#formMsg').text('You currently have ' + bCount + ' errors that need to be fixed before the form will be submitted.').show();
	}
}

function checkLength(o,n,min,max) {

	if ( o.val().length > max || o.val().length < min ) {
		o.addClass('error');
		updateTips("Length of " + n + " must be between "+min+" and "+max+".");
		bValid = bValid && false;
	} else {
		bValid = bValid && true;
	}

}

function checkSelection(o,n){
	if( o.val().length < 1 ){
		o.addClass('error');
		updateTips("Select a choice from " + n + ".");
		bValid = bValid && false;
	} else {
		bValid = bValid && true;
	}
}

function checkRegexp(o,regexp,n) {

	if ( !( regexp.test( o.val() ) ) ) {
		o.addClass('error');
		updateTips(n);
		bValid = bValid && false;
	} else {
		bValid = bValid && true;
	}

}

function inStock(stock, side){
			
		//$('option[class=' + side + ']').css({'color':'#CCCCCC'});
		$('option[class=' + side + '][value!=0]').hide();
		
		opt1 = $('#option_' + side + '_1').val();
		opt2 = $('#option_' + side + '_2').val();
		opt3 = $('#option_' + side + '_3').val();
		opt4 = $('#option_' + side + '_4').val();
		opt5 = $('#option_' + side + '_5').val();
		
		var a;
		var b;
		var c;
		var d;
		var e;
		
		for (a in stock){
			if(a == opt1 || opt1 == 0 || opt1 == null){
				for(b in stock[a]){
					if(b == opt2 || opt2 == 0 || opt2 == null){
						for(c in stock[a][b]){
							if(c == opt3 || opt3 == 0 || opt3 == null){
								for(d in stock[a][b][c]){
									if(d == opt4 || opt4 == 0 || opt4 == null){
										for(e in stock[a][b][c][d]){
											if(e == opt5 || opt5 == 0 || opt5 == null){																												
												if(stock[a][b][c][d][e].instock == 'true'){																																												
													//$('#opt_' + side + '_1_' + a).css({'color':'#000000'});
													//$('#opt_' + side + '_2_' + b).css({'color':'#000000'});
													//$('#opt_' + side + '_3_' + c).css({'color':'#000000'});
													//$('#opt_' + side + '_4_' + d).css({'color':'#000000'});
													//$('#opt_' + side + '_5_' + e).css({'color':'#000000'});
													$('#opt_' + side + '_1_' + a).show();
													$('#opt_' + side + '_2_' + b).show();
													$('#opt_' + side + '_3_' + c).show();
													$('#opt_' + side + '_4_' + d).show();
													$('#opt_' + side + '_5_' + e).show();

												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
		
		canBuy(stock, side);
}

function canBuy(stock, side){
			
		$('#add_' + side).attr('src', '/images/layout/chooseoptions.gif').addClass('noHand');
		
		opt1 = $('#option_' + side + '_1').val();
		opt2 = $('#option_' + side + '_2').val();
		opt3 = $('#option_' + side + '_3').val();
		opt4 = $('#option_' + side + '_4').val();
		opt5 = $('#option_' + side + '_5').val();
		
		var a;
		var b;
		var c;
		var d;
		var e;
		
		for (a in stock){
			if(a == opt1 || opt1 == null){
				
				if(opt1 != 0 && $('#option_' + side + '_1:visible').html()){ 
					$('#option_' + side + '_1').before('<span class="selOption">' + $('#option_' + side + '_1>option:selected').text() + '</span>'); 
					$('#option_' + side + '_1').hide();
					$('#option_' + side + '_2').show();
				}
				
				for(b in stock[a]){
					if(b == opt2 || opt2 == null){
						
						if(opt2 != 0 && $('#option_' + side + '_2:visible').html()){ 
							$('#option_' + side + '_2').before('<span class="selOption">' + $('#option_' + side + '_2>option:selected').text() + '</span>'); 
							$('#option_' + side + '_2').hide();
							$('#option_' + side + '_3').show();
						}
						
						for(c in stock[a][b]){
							if(c == opt3 || opt3 == null){
								
								if(opt3 != 0 && $('#option_' + side + '_3:visible').html()){ 
									$('#option_' + side + '_3').before('<span class="selOption">' + $('#option_' + side + '_3>option:selected').text() + '</span>'); 
									$('#option_' + side + '_3').hide();
									$('#option_' + side + '_4').show();
								}
				
								for(d in stock[a][b][c]){
									if(d == opt4 || opt4 == null){
										
										if(opt4 != 0 && $('#option_' + side + '_4:visible').html()){ 
											$('#option_' + side + '_4').before('<span class="selOption">' + $('#option_' + side + '_4>option:selected').text() + '</span>'); 
											$('#option_' + side + '_4').hide();
											$('#option_' + side + '_5').show();
										}
										
										for(e in stock[a][b][c][d]){
											if(e == opt5 || opt5 == null){	
											
												if(opt5 != 0 && $('#option_' + side + '_5:visible').html()){ 
													$('#option_' + side + '_5').before('<span class="selOption">' + $('#option_' + side + '_5>option:selected').text() + '</span>'); 
													$('#option_' + side + '_5').hide();
												}
											
												if(stock[a][b][c][d][e].instock == 'true'){
													$('#price_' + side).html(stock[a][b][c][d][e].price);
													$('#add_' + side).attr('src', '/images/layout/addtocart.gif').removeClass('noHand');
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
		
}

function canAdd(stock, side){
		
		opt1 = $('#option_' + side + '_1').val();
		opt2 = $('#option_' + side + '_2').val();
		opt3 = $('#option_' + side + '_3').val();
		opt4 = $('#option_' + side + '_4').val();
		opt5 = $('#option_' + side + '_5').val();
		
		var a;
		var b;
		var c;
		var d;
		var e;
		
		for (a in stock){
			if(a == opt1 || opt1 == null){
				for(b in stock[a]){
					if(b == opt2 || opt2 == null){
						for(c in stock[a][b]){
							if(c == opt3 || opt3 == null){
								for(d in stock[a][b][c]){
									if(d == opt4 || opt4 == null){
										for(e in stock[a][b][c][d]){
											if(e == opt5 || opt5 == null){	
												if(stock[a][b][c][d][e].instock == 'true'){																																									
													return false;
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
		
		return true;
		
}

function resetStock(side){
	$('.form_' + side).find('select').each( function(){
		$(this).hide();
		$(this).val( $("#" + $(this).attr("id") + " option:first").val() );
	});
	
	$('.form_' + side).find('.selOption').remove();
	
	$('#option_' + side + '_1').show();
	
	$('#price_' + side).html($('#orig_price_' + side).html())
	
	if(side == 'L'){ inStock(stock_L, 'L'); }
	if(side == 'R'){ inStock(stock_R, 'R'); }
	if(side == 'Y'){ inStock(stock_Y, 'Y'); }
	if(side == 'M'){ inStock(stock_M, 'M'); }
}

function serializeID(obj){
	
	var objID = obj.attr('id');
	var vars = objID.split('_');
	var output = "";
	
	for (var i=0;i<vars.length;i = i + 2) {
		output = output + vars[i] + '=' + vars[(i + 1)];
		if(vars.length > (i + 2)){
			output = output + '&';
		}
	}
	
	return output;
}

function serializeIDOnly(obj){
	
	var objID = obj.attr('id');
	var vars = objID.split('_');
	var output = vars[1];
	
	return output;
}

Shadowbox.init({
	players: ['img','swf', 'iframe'],
	initialWidth: '640',
	initialHeight: '505'
});