// JavaScript Document
var global_url = '/ewinerysolutionsproductfeed?format=json&orderby=displayorder';
filter_list = {};
	
function load_details(id){
	//loop through objects, if one matches an element name then populate it
	$.each(base_list, function(i) {
		if(this.PRODUCTID == id){
			$.each(this, function(k,v){
				if($('.'+k).length > 0){
					if(k == 'ADDITIONALIMAGES'){
						$('.'+k).attr('src',v);
					} else {
						$('.'+k).html(v);
					}
                    //hide blank values
                    if(v.length != ''){
                        $('.'+k).parents('.item').show();
                    } else {
                        $('.'+k).parent('.item').hide();
                    }
				} else if(k == 'MARKETINGURL'){
                    
                    if(v.length > 0){
                        var new_page = 'http://'+document.domain+'/'+v;
                    } else {
                        var new_page = 'http://'+document.domain+'/index.cfm?method=storeproducts.showdrilldown&amp;productid='+id;
                    }
                    
                    //redraw facebook likes
                    redraw_fb(new_page);
                    
                    //redraw twitter
                    redraw_twitter(new_page);
                    
                }
			});
		}
	});
	
	//show loading wheel for tabs
	add_loading('.detail-block');
    
    //product url
    var product_url = '/index.cfm?method=storeproducts.showdrilldown&isquickinfo=1&productid='+id;
    var data = '';
	$.get(product_url,function(data){
		$('.detail-block').html(data);
		setup_tips();
		setup_add_to_cart();
        move_promo_prices();
        button_background('.add-to-cart');
        
		if($('#availableInventory').text().length > 0){
            var current_text = $('#availableInventory').text();
            if(current_text.indexOf('Available') >= 0){
                $('.inventory-message').css('position','static');
            }
			$('.inventory-message').show();
		}
        $('.product-detail').fadeIn();
        
	});
}

function redraw_fb(fb_url){
    $('html').attr("xmlns:og","http://www.facebook.com/2008/fbml").attr("xmlns:fb","http://www.facebook.com/2008/fbml");

	// Remove previously created FB like elements -- if they exist
	$('.fb-recommend').remove();
	$('#fb-root').empty();
    
    fb_like = '<fb:like href="'+fb_url+'" style="margin-top: -1px;" font="" show_faces="false" width="200" layout="button_count" send="false"></fb:like></div>';
    $('#facebook-div').html(fb_like);
    // Load in FB javascript SDK
	$('body').append('<div id="fb-root"></div>');
	window.fbAsyncInit = function() {
		FB.init({appId: '296500660838', status: true, cookie: true, xfbml: true});
	};
    (function() {
		var e = document.createElement('script'); e.async = true;
		e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
		document.getElementById('fb-root').appendChild(e);
	}());
    
}

function redraw_twitter(link){
    // remove current iframe
    $('#twitter-div iframe').remove();
    // append new link
    $('#twitter-div').html('<a data-via="LaCremaWines" data-count="horizontal" data-url="'+link+'" data-text="Check out this delicious wine!" class="twitter-share-button" href="http://twitter.com/share">Tweet</a>');
    //reload js
    (function() {
		var e = document.createElement('script'); e.async = true;
		e.src = document.location.protocol + '//platform.twitter.com/widgets.js';
		document.getElementById('twitter-div').appendChild(e);
	}());
    
}

function move_promo_prices(){
    if($('.applicable-coupon').length > 0){
        //move sale price to before the retail price
        $('.retail-prices').addClass('applied');
        //hide discount-savings
        $('.discount-savings').hide();
    } else {
        $('.discount-savings').html('');
        $('.promo-price').each(function(){
            $('.discount-savings').append($(this));
        });
    }
}

function load_catalog(url){
	//get the product category json
	$.getJSON(url,function(data){
		//store the complete product list in the global var
		base_list = data;
		format_catalog(base_list);
	});
}

function format_catalog(list){
	var scroll_count = 0;
	var click_diff = 0;
	//clear products area
	$('.jcarousel-skin-tango').remove();
	$('.product-list').append('<ul id="products-carousel" class="products jcarousel-skin-tango"></ul>');
	$.each(list, function(i) {
		if(parseInt(this.INVENTORY) && this.INVENTORY > 0){
			var curr_price = "$"+this.PRICE1;
		} else {
			var curr_price = this.INVENTORY_OUTOFSTOCKMESSAGE;
		}
		//create product
		$('.products').append('<li class="product" id="'+this.PRODUCTID+'"><div class="mask">&nbsp;</div><div class="product-image"><img src="'+this.IMAGELINK+'" /></div><div class="product-type">'+this.VARIETAL+'</div><div class="product-appellation">'+this.VINEYARDDESIGNATION+'</div><div class="bottom-line"><span class="product-vintage">'+this.VINTAGE+'</span><span class="spacer">&nbsp;</span><span class="price">'+curr_price+'</span></div></li>');
	});
	
	//initialize carousel
	//$('.products').jcarousel({scroll:5,wrap: 'circular'});
	$('.products').jcarousel({scroll:5});

	//show
	$('.products').fadeIn();
	
	//total items
	var total_products = $('.products li').length;
	var total_products_mod = total_products%5;

	$('.jcarousel-prev').click(function(){
		scroll_count-=1;
		click_diff = Math.abs((scroll_count*5)-total_products);
	});
	
	$('.jcarousel-next').click(function(){
		scroll_count+=1;
		click_diff= Math.abs((scroll_count*5)-total_products);
	});
	
	
	//action to load detail page
	$('.product').click(function(){
	
		//highlight product
		$('.product').removeClass('selected');
		$(this).addClass('selected');
		
		//load details
		load_details($(this).attr('id'));
		
	});
	if($('input[name="attributes_productid"]').length > 0){
		$('#'+$('input[name="attributes_productid"]').val()).click();
	} else {
		$('.product:first').click();
	}
	//show menu
	$('.filters-top').fadeIn();
}

function removeURLParam(param){
	var prefix= encodeURIComponent(param)+'=';
	var pars= query_string.split(/[&;]/g);
	for (var i=pars.length; i-- > 0;){
		if (pars[i].indexOf(prefix, 0)==0){
			pars.splice(i, 1);
		}
	}

	if (pars.length > 0){
		return pars.join('&');
	}else{
		return '';	
	}
}

function setup_menu(){
	var newObj = {};
	//create menu actions
	$('.attribute-name').click(function(){
        var this_item = $('.attribute-name').index($(this));
        //hide all non-selected values
        $('.attribute-name').each(function(i){
            if($(this).parent().find('.remove-filter').length == 0 && i != this_item){
                $(this).parent().find('ul').slideUp();
            }
        });
		//if not selected, show values
        if($(this).parent().find('.remove-filter').length == 0){
            $(this).parent().find('ul').slideToggle();
        }
    });
	//create attribute-value actions
	$('.attribute-value').click(function(){
        var this_item = $('.attribute-name').index($(this).parents('.attribute').find('.attribute-name'));
		var filter_name = $(this).parent().parent().attr('id');
		var filter_value = $(this).attr('id');
		var remove_index;
		if($(this).hasClass('remove-filter')){
            //remove the filter from the querystring
			query_string = removeURLParam(filter_name);
			//remove selection
			$(this).removeClass('remove-filter');
			 //hide all non-selected values
            $('.attribute-name').each(function(i){
                if($(this).parent().find('.remove-filter').length == 0 && i != this_item){
                    $(this).parent().find('ul').slideUp();
                }
            });
            //show all options
			$(this).parent().find('li').show();
			//remove filter
			$.each(filter_list,function(k,v){
				if(k == filter_name){
					delete filter_list[filter_name]
				}
			});
		} else {
			//create new querystring
			query_string = query_string+'&'+filter_name+'='+filter_value;
			//hide other options
			$(this).parent().find('li').hide();
			//$(this).removeClass('attribute-value');
			$(this).addClass('remove-filter');
			//$(this).unbind();
			$(this).show();
			//add new filter
			filter_list[filter_name] = filter_value;
		}
		//load_catalog(global_url+query_string);			
		update_catalog(filter_list);
	});
}

function update_catalog(filter_list){
	//create new catalog object
	var new_list = [];
	var push_array = [];
	for(k in base_list){
		new_list.push(base_list[k]);
	}
	//fix this loop, need to be able to have more than one filter
	$.each(new_list, function(i){
		$.each(filter_list,function(k,v){
			if(new_list[i] && new_list[i][k] != v){
				delete new_list[i];
			}
		});
	});
	for(k in new_list){
		if(new_list[k]){
			push_array.push(new_list[k]);
		}
	}
	if(push_array.length > 0){
		format_catalog(push_array);
		adjust_menu(push_array);
	} else  {
		alert('No wines match your search.');
	}
}
function adjust_menu(push_array){
	//loop through filter values
	$('.attribute-value').each(function(curr_attr_val){
		var keep_filter = 0;
		var attribute_id = $(this).parent().parent().attr('id');
		var attribute_val = $(this).attr('id');
		$(push_array).each(function(i){
			if(push_array[i][attribute_id] == attribute_val){
				keep_filter = 1;
			}
		});
		if(keep_filter == 1){
			$(this).removeClass('hide');
		} else {
			$(this).addClass('hide');
		}
	});
	
	//after filter_value loop loop through filters, if all of their children are hid then hide top 
	$('.attribute').each(function(i){
		var total_values = $(this).find('.attribute-value').length;
		var hidden_values = $(this).find('.hide').length;
		if(total_values == hidden_values){
			$(this).addClass('hide');
		} else {
			$(this).removeClass('hide');
		}
	});
}
function setup_tips(){
	$(".RATING-BOX").hover(
		function(){$(this).find('.tip').fadeIn();}
		,function(){$(this).find('.tip').fadeOut();}
	);
}
function setup_add_to_cart(){
    $('.view-cart').click(function(){
		show_modal();
	});
	//add to cart
	$('.add-to-cart').click(function(){
		show_modal();
		var querystring = $(this).parents('form').serialize();
		var action = $(this).parents('form').attr('action');
		if($('#layAuthenticationHolder').length > 0){
			$('.modal').html($('#layAuthentication').html());
            $('.close-cart').click(function(){hide_modal()});
			$('#submitButton').click(function(){
				state_querystring = 'shippingstate='+$('select[name="ShippingStates"]').val()+'&referrer='+$('input[name="referrer"]').val();
				if($('select[name="ShippingStates"]').val() != 'false'){
					add_loading('.cart-wrapper');
					$.post($('form[name="selectStates"]').attr('action')+'&'+state_querystring,function(){
						$('#layAuthenticationHolder').remove();
						add_to_cart(querystring,action);
					})
				}
				return false
			});
		} else {
			add_to_cart(querystring,action);
		}
	});
}

function add_to_cart(querystring,action){
	//remove current cart
	add_loading('.cart-wrapper');
	//post url
	var random_num = Math.floor(Math.random()*9001);
	var add_url = action + '&' + querystring + '&c='+random_num;
	$.post(add_url,function(data){
		get_cart();
	});
}

function get_cart(){
	var random_num = Math.floor(Math.random()*9001);
	var cart_url = '/index.cfm?method=storecart.showcart&ajax=1&c='+random_num;
	$.get(cart_url, function(data){
		$('.cart-wrapper').html(data);
		$('.remove-item').click(function(){
			if (!confirm('Are you sure you want to remove this item from your cart?')){
				return false
			} else {
				//put up loading
				add_loading('.cart-wrapper');
				//remove item and reload cart
				$.post($(this).attr('href'),function(){get_cart();});
				return false
			}
		});
		apply_coupons();
		$('.close-cart').click(function(){hide_modal()});
		$('.cart-qty').text($('.subtotal-qty:first').text());
        //if the qty is 0 then remove the checkout-options. if it is greater than 0 and the checkout options don't exist then add them.
		if(parseInt($('.subtotal-qty:first').text()) == 0 && $('.checkout-options').length > 0){
			$('.checkout-options').remove();
		} else if(parseInt($('.subtotal-qty:first').text()) > 0 && $('.checkout-options').length == 0){
			$('.discount-savings').before('<span class="checkout-options"><a class="view-cart">View Cart</a><a href="/index.cfm?method=storecart.showcart" class="check-out">Check Out</a></span>');
		}
		//style buttons
        button_background('.cart-bottom .check-out');
        button_background('.apply-button');
	});
}

function show_modal(){
	$('.big-black').css('height',$('#wrap').height()+'px');
	$('.big-black').click(function(){hide_modal();});
	$('.big-black').fadeIn();
	$('.modal').fadeIn();
}

function hide_modal(){
	$('.modal').fadeOut();
	$('.big-black').fadeOut();
}

function add_loading(target){
	$(target).html('<img style="margin:auto;" src="/assets/images/global/ajax-loader.gif" />');
}

function apply_coupons(){
	$('.apply-button').click(function(){
		if($('input[name="CouponCodes"]').val() != ''){
			var coupon_url = $('form[name="coupon_form"]').attr('action')+'&'+$('form[name="coupon_form"]').serialize()+'&ajax=1';
			add_loading('.cart-wrapper');
			$.post(coupon_url,function(){
				get_cart();
			})
		} else {
			$('.error').html('Please enter a valid coupon code.');
		}
	});
}

function mask_that(element,padding,orientation){
		//mask html
		var mask_html = '<div class="round-mask"><div class="left"><img src="/assets/images/global/'+element+'-on-left.png" /></div><div class="right"><img src="/assets/images/global/'+element+'-on-right.png" /></div></div>'
		//create the mask element
		$('.'+element + ' .round').each(function(i){
			if(orientation=='horizontal'){
				//get element curr width
				var link_width = $(this).width();
				//append the mask html
				$(this).append(mask_html);
				//resize left element
				$(this).find('.round-mask .left').width($(this).find('.round-mask .left').width()+link_width);
			} else {
				//get element curr width
				var link_height = $(this).height();
				//append the mask html
				$(this).append(mask_html);
				//resize left element
				$(this).find('.round-mask .left').height($(this).find('.round-mask .left').height()+link_width);
			}
			$(this).hover(
                function(){$(this).toggleClass('on');}
                ,function(){$(this).toggleClass('on');$(this).find('input').blur();}
            );
		});
	}

function button_background(element_selector){
    var valueArray = element_selector.split(",");
    for(var i=0; i<valueArray.length; i++){
        $(valueArray[i]).each(function(j){
            //create the button background
            var wrapper_html = '<div class="button-left">'+$(this).text()+'</div><div class="button-right">&nbsp;</div>';
            //populate the element with the new html
            $(this).html(wrapper_html);
            //create roll over events
            $(this).hover(function(){$(this).addClass('button-on');},function(){$(this).removeClass('button-on');});
        });
    }
}

function dropper(element_selector){
    $(element_selector).hover(
        function(){$(this).find('.dropper').show();}
        ,function(){$(this).find('.dropper').hide();$(this).find('input').blur();}
    );
    sub_nav_hover(element_selector);
}

function sub_nav_hover(element_selector){
    $(element_selector+' .dropper').hover(
        function(){
            $(this).parent().find('a').addClass('button-on');
        }
        ,function(){
            $(this).parent().find('a').removeClass('button-on');
        }
    );
}
    
function newsletter_signup(){
		$('input[name="newsletter_signup"]').click(function(){
			if($(this).is(':checked') == true){
				$.post('/index.cfm?method=newsletter.addMemberToNewsletter&memberid='+$('input[name="m_3"]').val());
			} else {
				$.post('/index.cfm?method=newsletter.removeMemberFromNewsletter&memberid='+$('input[name="m_3"]').val());
			}
		});
}
