var months = [
	"January",
	"February",
	"March",
	"April",
	"May",
	"June",
	"July",
	"August",
	"September",
	"October",
	"November",
	"December"
];
var days = [
	"Sunday",
	"Monday",
	"Tuesday",
	"Wednesday",
	"Thursday",
	"Friday",
	"Saturday"
];


function modalMessage(message){
	$.colorbox({html: message});
}

function shippingModal(){
	var info = "<div style=\"400px;\"><p>All orders are charged are charged a $10.95 flat-rate shipping fee unless otherwise noted by the item.</p><p>For example, some items ship free, while others may be assessed an additional oversized charge.</p></div>";
	modalMessage(info);
}

function siteSearch(){
	var q = $("#SearchQuery").val();
	var loc = "http://www.google.com/search?q="+q+"%20site:kettletokeg.com";
	window.location = loc;
}

function parseFacebookDate(str){
	//ex. 2010-07-29T16:24:16+0000
	var dateAndTime = str.split("T");
	
	var date = dateAndTime[0].split("-");
		var year = date[0];
		var month = date[1]-1;
		var day = date[2];
		
	var fullTime = dateAndTime[1].split("+");
	var time = fullTime[0].split(":");
		var hour = time[0];
		var minute = time[1];
		var second = time[2];
		
	var timeZone = fullTime[1];
	
	var ret = new Date(year, month, day, hour, minute, second);
	return ret;
}
function displayFacebookFeed(targetDIV){
	var el = $("#"+targetDIV)
	el.html("");
	
	$.ajax({
		type: 'get',
		url: '/AJAX.php',
		data: {query: 'facebook'},
		dataType: 'json',
		complete: function(data){
			var feed = jQuery.parseJSON(data.responseText);
			var output = "<div class=\"facebookFeed\" style=\"display: none\">";
			
			for(var index in feed.data){
				var obj = feed.data[index];
				if(obj['to']){
					continue;
				}
				
				output += "<div class=\"feedItem\">";
				
				var name = "<a class=\"name\" target=\"_blank\" href=\"http://www.facebook.com/pages/Suncook-NH/Kettle-to-Keg-Suncook-NH/372437033597\">"+obj['from']['name']+"</a>";
				var message = "";
				if(obj['message']){
					message = obj['message'];
				}
				var pic = "<img class=\"pic\" src=\"http://graph.facebook.com/372437033597/picture\" />";
				var header = "<div class=\"header\">"+pic+" "+name+" "+message+"</div>";
				
				
				var picture = "";
				if(obj['picture']){
					picture = "<img src=\""+obj['picture']+"\" alt=\"\" />";
				}
				
				var name = "";
				if(obj['name']){
					name = obj['name'];
				}
				
				var link = "";
				if(obj['link']){
					link = obj['link'];
				}
				
				var attachment = "";
				switch(obj['type']){
					case 'photo':
						attachment = "<a class=\"img\" href=\""+link+"\">"+picture+"</a>" + "<br />" + "<a class=\"name\" href=\""+link+"\">"+name+"</a>";
						break;
					case 'link':
						if(picture){
							picture = "<a class=\"link\" href=\""+link+"\">"+picture+"</a>";
						}
						name = "<a class=\"name\" href=\""+link+"\">"+name+"</a>";
						
						var description = "";
						if(obj['description']){
							description = "<br />"+obj['description'];
						}
						attachment = picture + name + description;
						break;
					case 'status':
						break;
				}
				
				
				attachment = "<div class=\"attachment "+obj['type']+"\">"+attachment+"</div>";
				
				var icon = "";
				if(obj['icon']){
					icon = "<img class=\"icon\" src=\""+obj['icon']+"\" alt=\"\" align=\"top\"/>";
				}
				var postedDate = parseFacebookDate(obj['created_time']);
				postedDate = new Date(postedDate.getTime() - (1000 * 60 * 60 * 4));
				var oneWeek = 1000 * 60 * 60 * 24 * 5;
				var now = new Date();
				var oneWeekAgo = now.getTime() - oneWeek;
				
				if(postedDate.getTime() >= oneWeekAgo){
					posted = days[postedDate.getDay()];
				}
				else{
					posted = months[postedDate.getMonth()]+" "+postedDate.getDate();
				}
				
				var hour = postedDate.getHours();
				if(hour > 12){
					hour -= 12;
				}
				else if(hour == 0){
					hour = 12;
				}
				var minute = postedDate.getMinutes();
				posted += " at "+hour+":"+minute;
				
				
				var footer = "<div class=\"footer\">"+icon+" "+posted+"</div>";
				output += header+attachment+footer;
				output += "</div>";
			}
			output += "</div>";
			
			el.html(output);
			$("#"+targetDIV+" DIV.facebookFeed").fadeIn();
		}
	});
}

function parseTwitterDate($string){
	//"Mon, 02 Aug 2010 17:52:27 +0000"
	var day = $string.substr(0,3);
	var mon = $string.substr(8,3);
	var date = Number($string.substr(5,2));
	var hour = Number($string.substr(17,2)) - 3;
	if(hour < 0){
		hour += 24;
	}
	var min = $string.substr(20,2);
	
	var ampm = "am";
	if(hour >= 12){
		hour -= 12;
		ampm = "pm";
	}
	if(hour == 0){
		hour = 12;
	}
	return (day+", "+mon+" "+date+" at "+hour+":"+min+ampm);
}
function displayTwitterFeed(targetDIV){
	var el = $("#"+targetDIV)
	el.html("");
	
	$.ajax({
		type: 'get',
		url: '/AJAX.php',
		data: {query: 'twitter'},
		dataType: 'text',
		complete: function(data){
			var feed = jQuery.parseJSON(data.responseText);
			
			var output = "<div class=\"twitterFeed\" style=\"display: none\">";
			for(var i in feed){
				var tweet = feed[i];
				var text = tweet['title'];
				var posted = tweet['pubDate'];
				var link = tweet['link'];
				output += "<div class=\"feedItem\">";
				output += "<a href=\""+link+"\" target=\"_blank\" class=\"twitter\">"+text+"<\/a><br />";
				output += "<span class=\"posted\">"+parseTwitterDate(posted)+"<\/div>";
				output += "<\/div>";
			}
			output += "<\/div>";

			el.html(output);
			$("#"+targetDIV+" DIV.twitterFeed").fadeIn();
		}
	});
}

function displayFeed(id){
	$("A.feedLink IMG").each(function(){
		var src = $(this).attr('src');
		$(this).attr('src', src.replace("-on", "-off"));
	});
	
	var img = $("#"+id+"FeedLink IMG");
	img.attr('src', img.attr('src').replace("-off", "-on"));
	
	if(id == "Facebook"){
		displayFacebookFeed("SocialFeedsContent");
	}
	else if(id == "Twitter"){
		displayTwitterFeed("SocialFeedsContent");
	}
}
	
function getProductInfo(productID){
	$.ajax({
		url: '/AJAX.php?query=productInfo',
		type: 'post',
		data: {
			id: productID
		},
		complete: function(response){
			$("#ProductInfo").html(response.responseText);
		}
	});
}
	
function getProductInfo_DEV(productID){
	$.ajax({
		url: '/AJAX.php?query=productInfo_DEV',
		type: 'post',
		data: {
			id: productID
		},
		complete: function(response){
			$("#ProductInfo").html(response.responseText);
			$.colorbox({
				inline: true,
				href: "#ProductInfo",
				width: 700,
				height: 350
			});
		}
	});
}

function addProductToCart(productID, qty){
	$.ajax({
		url: '/AJAX.php?query=addToCart',
		type: 'post',
		data: {
			id: productID,
			qty: qty
		},
		async: false,
		complete: function(response){
			$("#MiniCartContents").html(response.responseText);
			$.colorbox.close();
		}
	});
}

function addProductModal(productID){
	$.ajax({
		url: '/AJAX.php?query=addProductModal',
		type: 'post',
		data: {id: productID},
		complete: function(response){
			$("#AddProductModal").html(response.responseText);
			$.colorbox({
				inline: true,
				href: "#AddProductModal"
			});
		}
	});
}

function removeFromCart(index){	
	$.ajax({
		url: '/AJAX.php?query=removeFromCart',
		type: 'post',
		data: {
			n: index
		},
		complete: function(response){
			refreshCart();
			addProductToCart();
		}
	});
}

function refreshCart(){
	$.ajax({
		url: '/AJAX.php',
		type: 'get',
		data: {
			query: 'shoppingCart'
		},
		complete: function(response){
			$("#ShoppingCart").html(response.responseText);
			addProductToCart();
		}
	});
}

function emptyCart(){
	$.ajax({
		url: '/AJAX.php',
		type: 'get',
		data: {
			query: 'emptyShoppingCart'
		},
		complete: function(response){
			refreshCart();
		}
	});
}


function saveQuantities(){
	var qty = [];
	var inputs = $("INPUT[name^='item_quantity']");
	inputs.each(function(){
		qty.push($(this).val());
	});
	
	$.ajax({
		url: "/AJAX.php?query=updateCartQuantities",
		type: 'post',
		data: {qty: qty},
		complete: function(response){
			if(response.responseText == 'ok')
			{
				window.location.reload();
			} else {
				modalMessage("Sorry, there was an error with your request.");
			}
		}
	});
}

function refreshProducts(){
	$.ajax({
		url: '/AJAX.php',
		type: 'get',
		data: {
			query: 'shopList',
			category: $("#CategorySelect").val(),
			search: $("#StoreSearch").val()
		},
		complete: function(response){
			$("#ShopContent").html(response.responseText);
		}
	});
}
