(function($) {

	/* STORE */

	store = {

		dir : '../store/',

		cnt : '#store .content',
		cart : '#cart-items',

		products : [],
		cart_items : [],

		init: function(){

			this.getProducts();
			this.getCartItems();


			$('#checkout').click(function(){
				store.checkout();
				return false;
			});

		},

		getProducts: function(){

			var p = [];

			$.getJSON('../store/uc_ajax/products', function(data) {

				if(data.status == 'success'){

					$.each(data.products, function(key, val) {
						p.push(val);
					});

					store.products = p;
					store.loadProducts();

				}else{
					alert('There was a problem getting product data...');
				}

			});



		},

		getCartItems: function(){

			var c = [];

			$.getJSON('../store/uc_ajax/cart/view', function(data) {

				if(data.status == 'success'){

					$.each(data.cart.items, function(key, val) {
						c.push(val);
						//console.log(val);
					});

					store.cart_items = c;
					store.populateCart();

				}else{
					alert('There was a problem getting cart data...');
				}

			});

		},

		loadProducts: function(){

			var divs = $('<div />').attr('id', 'store-products');
			var cnt = $(store.cnt);

			$.each(this.products, function(key,p) {

				/*
language": "en", "status": "1", "created": "1296343199", "changed": "1296347438", "comment": "0", "promote": "0", "sticky": "0", "tnid": "0", "translate": "0", "title": "Example Product", "body": "This is a simple example product that you can modify or delete. Use it to test checkout for a shippable item.", "teaser": "This is a simple example product that you can modify or delete. Use it to test checkout for a shippable item.", "format": "1", "model": "PRODUCT", "list_price": "15.00000", "cost": "5.00000", "sell_price": "10.00000", "weight": "5", "weight_units": "lb", "length": "0", "width": "0", "height": "0", "length_units": "in", "pkg_qty": "0", "default_qty": "1", "ordering": "0", "shippable": "1", "field_image_cache": [ { "fid": "4", "list": "1", "data": { "alt": "", "title": "" }, "uid": "4", "filename": "absolute august.jpg", "filepath": "sites/default/files/absolute august.jpg", "filemime": "image/jpeg", "filesize": "1116760", "status": "1", "timestamp": "1296347433" } ], "taxonomy": { "1": { "tid": "1", "vid": "1", "name": "Products", "description": "", "weight": "0" } }, "flatrate": [  ], "shipping_type": "small_package", "shipping_address": {  } }, { "nid": "4", "language": "", "status": "1", "created": "1296345980", "changed": "1296347294", "comment": "0", "promote": "1", "sticky": "0", "tnid": "0", "translate": "0", "title": "Test: product", "body": "This is the test description. You like?", "teaser": "This is the test description. You like?", "format": "1", "model": "1", "list_price": "0.00000", "cost": "1090.00000", "sell_price": "1000.00000", "weight": "0", "weight_units": "lb", "length": "0", "width": "0", "height": "0", "length_units": "in", "pkg_qty": "2", "default_qty": "1", "ordering": "0", "shippable": "1", "field_image_cache": [ { "fid": "3", "list": "1", "data": { "alt": "", "title": "" }, "uid": "4", "filename": "Guitar_Hero_III.jpg", "filepath": "sites/default/files/Guitar_Hero_III_0.jpg", "filemime": "image/jpeg", "filesize": "490438", "status": "1", "timestamp": "1296347288" } ], "taxonomy": { "1": { "tid": "1", "vid": "1", "name": "Products", "description": "", "weight": "0" } }, "flatrate": [  ], "shipping_type": "small_package", "shipping_address"
				*/

				var div_row = $('<div />');

                // TODO: default image or no image?
                var im = '';
                try {
                  im = store.dir + p.field_image_cache[0].filepath;
                } catch(e) {}

				var price = '$'+Math.abs(p.sell_price);

				var div = $('<div />').attr({'class':'product-cnt', 'id':'prod-'+p.nid});
				var div_title = $('<h3 />').attr({'class':'product-title'}).text(p.title+' ('+price+')');
				var div_body = $('<div />').attr({'class':'product-body'}).text(p.body);
				//var div_price = $('<div />').attr({'id':'prod-'+p.nid}).text('$'+Math.abs(p.sell_price));
				var div_im = $('<div />').append($('<img />').attr({'src':im, 'title':p.title, 'alt':p.title, 'width':226, 'class':'product-image'}));

                // handle the attributes
                var div_attributes = $('<span />');
                if(typeof p.attributes != 'undefined') {
                  for(var $i in p.attributes) {
                    var $attribute = p.attributes[$i];
                    // build select
                    var sel = $('<select />').attr('name', 'attributes[' + $attribute.aid + ']');
                    for(var $i in $attribute.options) {
                      var $option = $attribute.options[$i];
                      var $price = $option.price;
                      if(parseInt($price) > 0) {
                        $option.name += ', +' + format_money($price);
                      }
                      sel.append('<option value="'+$option.oid+'">'+$option.name+'</option>');
                    }
                    // build label + select
                    var label = $('<lable />').text($attribute.default_label);
                    div_attributes.append(label, sel);
                  }
                }

                var addtocart = $('<div />').append($('<a />').attr({'href':'#', 'class':'cart-link'}).text('Add to Cart')).data('item', {id:p.nid}).click(function(e){
                  var item = $(this).data('item');
                  store.addToCart({id:item.id});
                  e.preventDefault();
				});

                var form = $('<form />').attr('id', 'form-product-' + p.nid);
                form.append(div_title, div_im, div_attributes, addtocart, div_body);
                div.append(form);
				divs.append(div);

				if(key%2==1){
					var div_cf = $('<div />').attr('class','cf');
					divs.append(div_cf);
				}else{
					div.addClass('product-cnt-left');
				}

			});


			cnt.append(divs);

		},

		populateCart: function(){

			var cnt = $(store.cart);
			var ul = $('<ul />');

			if(this.cart_items.length>0){
				$.each(this.cart_items, function(i, p) {

					//remove from cart
					var delfromcart = $('<span />').append($('<a />').attr({'href':'#'}).text('(remove)').data('nid',p.nid).click(function(){
						var id = $(this).data('nid');
						store.deleteFromCart(id);
					}));
					var li = $('<li />').attr('class','product-title').text(p.title+' ('+p.qty+')').append(delfromcart);
					ul.append(li);

				});
			}else{
				var li = $('<li />').text('Your cart is empty.');
				ul.append(li);
			}

			cnt.empty().prepend(ul);

		},

		addToCart: function(item){
          var $form = $('#form-product-'+item.id);
			$.post('../store/uc_ajax/cart/add/'+item.id, $form.serialize(), function(data) {
				//console.log(id);
				if(data.status == 'success'){
					store.getCartItems();
				}else{
					alert('There was a problem adding that item to your cart.');
				}
			}, "json");

			return false;

		},

		deleteFromCart: function(id){

			$.post('../store/uc_ajax/cart/delete/'+id, {quantity: 1}, function(data) {
				store.getCartItems();
			}, "json");

			return false;

		},

		checkout: function(){

			var win = window.open('../store/cart','chkout');
			win.focus();

		}

	}




	/* END STORE */


	getFlickr = function(set_id, div){

		if(typeof(div)=='object' && div !=null){
		if( (div.data('loaded') != true) && (set_id != null) ){

			var apikey = '67d81c4b0108d8be68e46eda2d6cd2ea';
			var url = 'http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=' + apikey + '&photoset_id=' + set_id + '&extras=url_m&format=json&jsoncallback=?';
			$.getJSON(url, function(data){
				$.each(data.photoset.photo, function(i,item){

					var w = 476;
					var h = item.height_m / ( item.width_m / w );
					var im = $("<img />").attr({'src':item.url_m, 'alt':item.title, 'title':item.title, 'width':w, 'height':h}).appendTo(div); //'width':item.width_m, 'height':item.height_m

					//console.log(im.attr('src'));

				});


				div.find('img:last').load(function(){
					//div.slideDown('fast');
					if(data.photoset.photo.length>1){
						$(div).cycle('fade');
					}
				});


				div.data('loaded', true);

			});
		}
		}

	}


	submitReservationForm =	function(){

		var email = jQuery("#email").val().length > 0 ? jQuery("#email").val() : false;
		var nameFirst = jQuery("#name_first").val().length > 0 ? jQuery("#name_first").val() : false;
		var nameLast = jQuery("#name_first").val().length > 0 ? jQuery("#name_last").val() : false;
		var phone = jQuery("#phone").val().length > 0 ? jQuery("#phone").val() : false;
		var comments = $('#comments').val().length > 0 ? $('#comments').val() : false;
		var date1= jQuery("#inputDate").val().length > 0 ? jQuery("#inputDate").val() : false;
		var date2= jQuery("#toDate").val().length > 0 ? jQuery("#toDate").val() : false;
		var numguests= jQuery("#numGuests").val().length > 0 ? jQuery("#numGuests").val() : false;

		//error checking
		var error = false;
		jQuery(".error").text('');
		jQuery('#form_response').text('');

		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		email = emailReg.test(email) ? email : false;

		if((!nameFirst)||(!nameLast)){
			error = true;
			jQuery('.error').text('Please fill in all form fields before sending.');
		}else if(!email){
			error = true;
			jQuery('.error').text('Please enter a valid email address.');
		}else if(!phone){
			error = true;
			jQuery('.error').text('Please enter your phone number.');
		}


		if(!error){
			jQuery('#form_response').html('sending...');

			var str = jQuery('#reservation_form').serialize();

			//check optional fields not in form
			var roomsSelected = selectedRooms.length > 0 ? selectedRooms : false;
			if(roomsSelected){ str += '&roomids='+roomsSelected; }

			//alert('form sent test!: '+str);
			jQuery.ajax({
				type: "POST",
				url: "assets/templates/tsp/sendResForm.php",
				data: str,
				success: function(t){
					//jQuery('#form_response').text('Thank you, your request has been sent.  We will get back to you shortly.');
					var msg = t=='success' ? 'Thank you '+nameFirst+', your request has been sent.  We will get back to you shortly.' : 'Sorry, there was an error.  Please try again or <a href="mailto:info@tenutasantopietro.com">email us</a> directly.';
					jQuery('#form_response').html(msg);

				}
			});


		}


	}

	// ------------------------------------------------------- //



})(jQuery);

function format_money(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}

