// foxycart colorbox
var colorbox_width = "940px";
var colorbox_height = "529px";

// store object
var vcb_store = {
	
	// init
	init: function() {
		// vars
		vcb_store.has_console = typeof(console) !== 'undefined' && console != null;
		// inits
		vcb_store.customProductInit();
		vcb_store.emailInit();
		vcb_store.fadeNavInit();
		vcb_store.foxycartInit();
		vcb_store.galleryInit();
		vcb_store.productNavCustomOverlayInit();
	}
	
	// log
	,log: function(message) {
		if (vcb_store.has_console) console.log('[vcb store] ' + message);
	}
	
	// custom product init
	,customProductInit: function() {
		// if we're not on a custom product do nothing
		if (!$('#custom_product').length) return;
		// vars
		var $custom_product_designer = $('#custom_product_designer')
			,$custom_product_designer_intro = $('#custom_product_designer_intro')
			,$custom_product_designer_link = $('#custom_product_designer_link')
			,$slides = $custom_product_designer.find('.slide')
			,$dependencies = $custom_product_designer.find('.dependency');
		// intro on click
		$custom_product_designer_intro.click(function() {
			// fade out and remove
			$(this).fadeOut(200, 'swing', function() { $(this).remove(); });
		});
		// link scroll to stylings
		$custom_product_designer_link.click(function() {
			$.scrollTo($(this).attr('href'), 230);
			return false;
		});
		// init custom_product object
		vcb_store.custom_product = {
			'name': $('#custom_product_name').text()
			,'price': parseInt($('#custom_product_base_price').text())
			,'shared': $('#custom_product.shared').length
		};
		// select 1st slide
		$slides.eq(0).addClass('selected');
		// write slide nav
		var nav_html = Array();
		nav_html.push('<ul id="custom_product_designer_nav" class="dot_nav">');
		for (var i=0; i < $slides.length; i++) {
			nav_html.push('<li><a title="' + $slides.eq(i).find('.title').text() + '" href="javascript: vcb_store.customProductSlideShow(' + i + ');" class="' + (i == 0 ? 'selected' : '') + '">' + i + '</a></li>');
		};
		nav_html.push('</ul>');
		// insert slide nav
		$custom_product_designer.append(nav_html.join(''));
		// foreach slide
		$slides.each(function(i) {
			// vars
			var $slide = $(this)
				,$required_nav = $slide.find('.required_nav')
				,next_slide_title = $slides.eq(i + 1).find('.title').text();
			// slide specific init's
			switch($slide.attr('id')) {
				// upgrades
				case 'custom_product_upgrades':
					// vars 
					var $controls = $('#upgrade_controls')
						,$info = $('#upgrade_info');
					$info.find('li').eq(0).addClass('selected');
					// on controls <li> mouseover
					$controls.find('li').mouseover(function() {
						// id to show
						var id_to_show = $(this).find('.checkbox').attr('id');
						// hide old info
						$info.find('li.selected').removeClass('selected');
						// show new one
						$info.find('li[vcb_for=' + id_to_show + ']').addClass('selected');
					});
					// done
					break;
			}
			// if has required nav
			if ($required_nav.length) {
				// on <a> click
				$required_nav.find('a').click(function() {
					// vars
					var index_to_show = i + 1
						,previous_index_index = $('#custom_product_designer').data('previous_index_index');
					// if previously visited index and is greater than the next one, use it instead
					if (previous_index_index && (previous_index_index > index_to_show)) index_to_show = previous_index_index;
					// remove all selected
					$slide.find('a').removeClass('selected');
					// select this one
					$(this).addClass('selected');
					// this slide is completed
					$slide.addClass('completed');
					// show appropriate slide (next or previous state)
					vcb_store.customProductSlideShow(index_to_show);
					// and stopity stop them clickity clicks
					return false;
				});
			}
			// else
			else {
				// if last slide do nothing
				if (i >= $slides.length - 1) return false;
				// next button html
				var html = '<div class="slide_controls"><a href="javascript: vcb_store.customProductSlideShow(' + (i + 1) + ')" class="button_b"><span class="content">Next: ' + next_slide_title + '</span></a></div>';
				// add it in
				$slide.append(html);
				// can scroll past this w/out interaction
				$(this).addClass('completed');
			}
		});
		// if share'd product, update product from all the slides, take to the last stage
		// this needs to happen before the dependencies init or else they init wrong
		if (vcb_store.custom_product.shared) {
			// hide intro
			$('#custom_product_designer_intro').remove();
			// update all the sections
			$('#custom_product_designer .slide').each(function() {
				vcb_store.customProductUpdate($(this));
			});
			// go to last slide
			vcb_store.customProductSlideShow($('#custom_product_designer .slide').length - 1);
			// and do some scrolly action
			setTimeout(function() { $.scrollTo($('#custom_product_designer'), 230); }, 500);
		}
		// init dependencies
		$dependencies.each(function() {
			// vars
			var $depender = $('#' + $(this).data('for')).parents('li').eq(0)
				,depender_type = $(this).data('depender-type')
				,dependency_type = $(this).data('type')
				,dependency_values = $(this).data('values').split(',');
			// continue by dependency type
			switch(dependency_type) {
				// sizes
				case 'sizes':
					// foreach size on click
					$('#custom_product_sizes .badge_nav a').click(function() {
						// enable or no
						var enable = $.inArray($(this).find('.size_abbreviation').text(), dependency_values) > -1;
						// and update
						vcb_store.customProductDependencyUpdate($depender, depender_type, enable);
					});
					// foreach size initial init
					$('#custom_product_sizes .badge_nav a').each(function() {
						// enable or no
						var enable = $.inArray($(this).find('.size_abbreviation').text(), dependency_values) > -1;
						// and update
						vcb_store.customProductDependencyUpdate($depender, depender_type, enable);
					});
					// done
					break;
				// upgrades
				case 'upgrades':
					// foreach dependency value
					for (var i=0; i < dependency_values.length; i++) {
						// on clickity clickity
						$('#' + dependency_values[i]).click(function() {
							// enable or no
							var enable = $(this).is(':checked');
							// and update
							vcb_store.customProductDependencyUpdate($depender, depender_type, enable);
						});
						// for each initial init
						$('#' + dependency_values[i]).each(function() {
							// enable or no
							var enable = $(this).is(':checked');
							// and update
							vcb_store.customProductDependencyUpdate($depender, depender_type, enable);
						});
					};
					// done
					break;
			}
		});
		// share link on click (no idea why it needs the unbind)
		$('#share').unbind('click').click(function() {
			// replace-o-matic
			$(this).addClass('disabled');
			// send ajax request
			$.ajax({
				dataType: 'json'
				,type: 'GET'
				,url: $(this).attr('href')
				,success: function(json) {
					// error
					if (!json.success) {
						alert(json.message);
						return false;
					}
					// good to go, un disable
					$('#share').removeClass('disabled');
					// and show link
					vcb_store.customProductShareLinkShow(json.short_url);
				}
			});
			// and stop clickity click
			return false;
		});
	}
	
	// update a dependency
	,customProductDependencyUpdate: function($depender, depender_type, enable) {
		// which depender type
		switch(depender_type) {
			// upgrade
			case 'upgrade':
				// if enable, show and enable
				if (enable) {
					// restore state
					if ($depender.data('was_checked')) $depender.find('input').attr('checked', 'checked');
					// fade in and enable
					$depender.fadeTo(100, 1).find('input').attr('disabled', false);
				}
				// else disable it
				else {
					// store current state
					$depender.data('was_checked', $depender.find('input:checked').length);
					// fade out, uncheck and disable
					$depender.fadeTo(100, .5).find('input').removeAttr('checked').attr('disabled', true);
				}
				// done
				break;
			// color
			case 'color':
				// if enable show
				if (enable) $depender.removeClass('disabled');
				// else hide
				else $depender.addClass('disabled');
				// done
				break;
		}

	}
	
	// custom share link hide
	,customProductShareLinkHide: function() {
		$('#custom_product_summary').css('left', 0);
		$('#summary_overview').css('visibility', 'visible');
	}
	
	// custom share link show
	,customProductShareLinkShow: function(url) {
		$('#share_link').text(url);
		$('#custom_product_summary').css('position', 'absolute').animate({ left: '-400px' }, 250, 'swing', function() {
			$('#summary_overview').css('visibility', 'hidden');
		});
	}
	
	// custom product slides, show slide
	,customProductSlideShow: function(index_to_show) {
		// vars
		var $slides = $('#custom_product_designer .slide')
			,is_animating = $slides.filter('.animating').length
			,$slide_to_hide = $slides.filter('.selected')
			,index_to_hide = $slides.index($slide_to_hide)
			,$slide_to_show = $slides.eq(index_to_show)
			,slide_width = $slide_to_hide.width()
			,animate_direction = index_to_show > index_to_hide ? 1 : -1
			,$nav = $('#custom_product_designer_nav');
		// if currently animating no dice
		if (is_animating) return;
		// if slide_to_hide and slide_to_show are the same no dice
		if ($slide_to_hide.attr('id') == $slide_to_show.attr('id')) return false;
		// if moving forward and slide to hide hasn't been completed
		if (animate_direction == 1 & !$slide_to_hide.hasClass('completed')) {
			// error message
			alert($slide_to_hide.find('.error_message').html());
			// and stop
			return false;
		}
		// update custom_product object
		vcb_store.customProductUpdate($slide_to_hide);
		// hide current
		$slide_to_hide.addClass('animating').removeClass('selected').animate({ left: (slide_width * animate_direction * -1) + 'px' }, 400, 'swing', function() {
			// stop animating flag, reset positioning
			$(this).removeClass('animating').css('left', 0);
		});
		// show new
		$slide_to_show.css({ 'left': (slide_width * animate_direction) + 'px' }).addClass('animating').animate({ left: 0 }, 400, 'swing',function() {
			// stop animating flag, show selected flag
			$(this).addClass('selected').removeClass('animating');
		});
		// update nav
		$nav.find('.selected').removeClass('selected');
		$nav.find('a').eq(index_to_show).addClass('selected');
		// store last slide visited
		$('#custom_product_designer').data('previous_index_index', index_to_hide);
		// slide specific 'on show' stuff
		switch($slide_to_show.attr('id')) {
			// summary
			case 'custom_product_summary':
				// update the summary
				vcb_store.customProductSummaryUpdate();
				// done
				break;
		}
	}
	
	// update the custom product summary slide
	,customProductSummaryUpdate: function() {
		// foxycart URL and summary update vars
		var url_params = 'name=' + vcb_store.custom_product.name
			,total_price = vcb_store.customProductTotalPrice()
			,$summary_size = $('#summary_size')
			,$summary_style = $('#summary_style')
			,$summary_upgrades = $('#summary_upgrades')
			,$summary_colors = $('#summary_colors')
			,$summary_price = $('#summary_price')
			,shipping_weight = parseFloat($('#shipping_weight').attr('value'));
		// has size
		if ($summary_size.length) {
			// update summary html
			$summary_size.text(vcb_store.custom_product.size.name);
			// update url params
			url_params += '&size=' + vcb_store.custom_product.size.name.toUpperCase();
		}
		// has style
		if ($summary_style.length) {
			// udpate summary html
			$summary_style.text(vcb_store.custom_product.style.name + ' (' + vcb_store.custom_product.style.description + ')');
			// update url params
			url_params += '&style=' + vcb_store.custom_product.style.name;
		}
		// has upgrades section
		if ($summary_upgrades.length) {
			var upgrade_names = [];
			for (var i=0; i < vcb_store.custom_product.upgrades.length; i++) {
				upgrade_names.push(vcb_store.custom_product.upgrades[i].name);
			}
			// if has upgrade
			if (upgrade_names.length) {
				// string it
				var upgrade_string = upgrade_names.join(', ');
				// update summary html
				$summary_upgrades.html(upgrade_string);
				// update url params
				url_params += '&upgrades=' + upgrade_string;
			}
			// no upgrades
			else {
				// update summary html
				$summary_upgrades.html('(None)');
				// update url params
				url_params += '&upgrades=None';
			}
		}
		// has colors
		if ($summary_colors.length) {
			var color_names = [];
			for (var i=0; i < vcb_store.custom_product.colors.length; i++) {
				color_names.push(vcb_store.custom_product.colors[i].name + ': ' + vcb_store.custom_product.colors[i].value);
			};
			// string it
			var color_string = color_names.join(', ');
			// update summary html
			$summary_colors.html(color_string);
			// update url params
			url_params += '&colors=' + color_string;
		}
		// update price
		$summary_price.text(total_price);
		url_params += '&price=' + total_price;
		url_params += '&weight=' + shipping_weight;
		// center em vertically
		$('#summary_overview, #summary_details, #summary_share').verticalCenter();
		// update share link URL
		$('#share').attr('href', '/shorten?long_url=' + ('http://' + document.location.host + '/share?' + encodeURIComponent(url_params)));
		// update add to cart URL
		$('#add_to_cart').attr('href', 'https://' + fcc.storedomain + '/cart?' + encodeURI(url_params));
	}
	
	// get the total price of the custom product
	,customProductTotalPrice: function() {
		// base price
		var price = vcb_store.custom_product.price;
		// if size
		if (typeof vcb_store.custom_product.size == 'object') {
			price += vcb_store.custom_product.size.price;
		}
		// if upgrades
		if (typeof vcb_store.custom_product.upgrades == 'object') {
			for (var i = vcb_store.custom_product.upgrades.length - 1; i >= 0; i--) {
				price += vcb_store.custom_product.upgrades[i].price;
			};
		}
		// return
		return price;
	}
	
	// update the custom product object by slide state
	,customProductUpdate: function($slide) {
		// by slide id
		switch($slide.attr('id')) {
			// sizes
			case 'custom_product_sizes':
				// vars
				var $selected = $slide.find('.required_nav a.selected')
					,name = $selected.length ? $selected.find('.badge_content').text() : false
					,price = $selected.length ? parseInt($selected.find('.price_amount').attr('price_increment')) : 0;
				// update object
				vcb_store.custom_product.size = { name: name, price: price };
				// done
				break;
			// style (handedness)
			case 'custom_product_hands':
				// vars
				var $selected = $slide.find('.required_nav a.selected')
					,name = $selected.length ? $selected.find('.name').text() : false
					,description = $selected.length ? $selected.find('.description').text() : false;
				// update object
				vcb_store.custom_product.style = { name: name, description: description };
				// done
				break;
			// colors
			case 'custom_product_colors':
				// vars
				var $color_options = $('#color_options li')
					,colors = [];
				// foreach color option
				$color_options.each(function() {
					// if disabled, do nothing
					if ($(this).hasClass('disabled')) return false;
					// vars
					var name = $(this).find('label').text()
						,value = $(this).find('option:selected').text();
					// add to array
					colors.push({ name: name, value: value });
				});
				// update object
				vcb_store.custom_product.colors = colors;
				// done
				break;
			// upgrades
			case 'custom_product_upgrades':
				// vars
				var $upgrade_options = $('#upgrade_controls li')
					,upgrades = [];
				// foreach upgrade option
				$upgrade_options.each(function() {
					// vars
					var checked = $(this).find('input:checked').length
						,name = $(this).find('label').text()
						,price = parseInt($(this).find('.price_amount').text());
					// if checked
					if (checked) {
						// add to upgrades
						upgrades.push({ name: name, price: price });
					}
				});
				// update object
				vcb_store.custom_product.upgrades = upgrades;
				// done
				break;
			// summary
			case 'custom_product_summary':
				// reset share link after delay
				setTimeout(function() { vcb_store.customProductShareLinkHide(); }, 500);
				// done
				break;
		}
	}
	
	// email spam stuff
	,emailInit: function() {
		$('a.email').each(function() {
			var pieces = $(this).text().split(' (at) ')
				,email_address = pieces[0] + '@' + pieces[1];
			$(this).attr('href', 'mailto:' + email_address).text(email_address);
		});
	}
	
	// fade style nav
	,fadeNavInit: function() {
		// get the list
		var $fade_nav = $('.fade_nav');
		// if no nav's do nothing
		if (!$fade_nav.length) return;
		// foreach nav
		$fade_nav.each(function() {
			// this fade nav
			var $current_nav = $(this);
			// <li> bindings
			$current_nav.find('li').mouseover(function() {
				// fade out the others
				$current_nav.find('li').not($(this)).stop().animate({ opacity: .5 }, 200);
			}).mouseout(function() {
				// fade em all in
				$current_nav.find('li').stop().animate({ opacity: 1 }, 200);
			});
		});
	}
	
	// foxycart init
	,foxycartInit: function() {
		// pre process
		fcc.events.cart.preprocess.add(vcb_store.foxycartPreProcess);
		// post process
		fcc.events.cart.postprocess.add(vcb_store.foxycartPostProcess);
	}
	
	// foxycart post processor
	,foxycartPostProcess: function() {
		// carts for comparison, array to hold the changes
		var start_cart_json = vcb_store.foxycartJson;
		// if no start cart do nothing
		if (!start_cart_json) return;
		// get lastest cart contents
		jQuery.getJSON('https://' + fcc.storedomain + '/cart?' + fcc.session_get() + '&output=json&callback=?', function(end_cart_json) {
			// loop through the start cart, check against end cart
			for (var i=0; i < start_cart_json.products.length; i++) {
				// if no product id/code is custom product, can ignore
				if (!start_cart_json.products[i].code) continue;
				// else check if the product is still in the cart
				var found = false;
				for (var c=0; c < end_cart_json.products.length; c++) {
					if (end_cart_json.products[c].code == start_cart_json.products[i].code) {
						found = true;
						break;
					}
				};
				// if the orig product isn't in the cart anymore, delete the lock
				if (!found) {
					// settings
					var settings = {
						data: { id: start_cart_json.products[i].code }
						,dataType: 'json'
						,success: function(json) {
							// console.log(json);
						}
						,type: 'GET'
					}
					// fire request
					$.ajax('/pre-made/unlock', settings);
				}
			};
		});
	}
	
	// foxycart pre processor
	,foxycartPreProcess: function(element, array) {
		// get the url vars of the add to cart link that was clicked
		var cart_vars = $.getUrlVars($(element).attr('href'));
		// store cart for laters
		vcb_store.foxycartJson = FC.json;
		// if no code (product id), ignore
		if (!cart_vars.code) return true;
		// if no quantity, use 1
		if (!cart_vars.quantity) cart_vars.quantity = 1;
		// item is
		var can_add = false
			,error_message = '';
		// configure request
		var	settings = {
			async: false
			,data: { id: cart_vars.code, quantity: cart_vars.quantity }
			,dataType: 'json'
			,error: function(jq_xhr, text_status, error_thrown) {
				error_message = text_status;
			}
			,success: function (json) {
				// problem locking
				if (!json.success) error_message = json.message;
				// else got it locked
				else {
					// else can add
					can_add = true;
					// add to foxy json
					vcb_store.foxycartJson.products.push({
						code: json.id
						,quantity: json.quantity
					});
				}
			}
			,type: 'GET'
		};
		// submit request
		$.ajax('/pre-made/lock', settings);
		// if can't add
		if (!can_add) {
			alert(error_message);
			return false;
		}
		// else rock n roll
		return true;
	}
	
	// galleries init
	,galleryInit: function() {
		// foreach gallery
		$('.gallery').each(function(gallery_index) {
			// select first <li>
			$(this).find('li').eq(0).addClass('selected');
			// if only one <li> stop here
			if ($(this).find('li').length < 2) return;
			// id
			var gallery_id = $(this).attr('id');
			// if no id
			if (!gallery_id) {
				var gallery_id = 'gallery_' + new Date().getTime() + '_' + gallery_index;
				$(this).attr('id', gallery_id);
			}
			// write nav html
			var nav_html = Array();
			nav_html.push('<ul id="' + gallery_id + '_nav" class="dot_nav gallery_nav">');
			// for each <li>
			$(this).find('li').each(function(li_index) {
				nav_html.push('<li><a href="javascript: vcb_store.galleryShow(\'' + gallery_id + '\', ' + li_index + '); " class="' + (li_index == 0 ? 'selected' : '') + '">' + li_index + '</a></li>');
			});
			nav_html.push('</ul>');
			// add nav html
			$(this).after(nav_html.join(''));
		});
	}
	
	// gallery show a slide
	,galleryShow: function(gallery_id, index_to_show) {
		// vars
		var $gallery = $('#' + gallery_id)
			,$slides = $gallery.find('li')
			,is_animating = $slides.filter('.animating').length
			,$slide_to_hide = $slides.filter('.selected')
			,index_to_hide = $slides.index($slide_to_hide)
			,$slide_to_show = $slides.eq(index_to_show)
			,slide_width = $slide_to_hide.width()
			,animate_direction = index_to_show > ($slides.index($slide_to_hide)) ? 1 : -1
			,$nav = $('#' + gallery_id + '_nav');
		// if currently animating no dice
		if (is_animating) return;
		// if slide_to_hide and slide_to_show are the same no dice
		if (index_to_hide == index_to_show) return false;
		// hide current
		$slide_to_hide.addClass('animating').removeClass('selected').animate({ left: (slide_width * animate_direction * -1) + 'px' }, 400, 'swing', function() {
			// stop animating flag, reset positioning
			$(this).removeClass('animating').css('left', 0);
		});
		// show new
		$slide_to_show.css({ 'left': (slide_width * animate_direction) + 'px' }).addClass('animating').animate({ left: 0 }, 400, 'swing', function() {
			// stop animating flag, show selected flag
			$(this).addClass('selected').removeClass('animating');
		});
		// update nav
		$nav.find('.selected').removeClass('selected');
		$nav.find('a').eq(index_to_show).addClass('selected');
	}
	
	// product nav custom overly init
	,productNavCustomOverlayInit: function() {
		// trigger to show
		$('#product_nav_custom').bind('mouseover', vcb_store.productNavCustomOverlayShow);
		// nav and menu listeners for triggering off
		$('#product_nav_custom, #product_nav_custom_overlay').mouseover(function() {
			// add class
			$(this).addClass('hover');
		}).mouseout(function() {
			// remove class
			$(this).removeClass('hover');
			// if not back on nav or overlay w/in timeframe, hide
			setTimeout(vcb_store.productNavCustomOverlayHide, 450);
		});
	}
	
	// product nav custom overlay hide
	,productNavCustomOverlayHide: function() {
		// if the nav or overlay is hovered, don't hide
		if ($('#product_nav_custom.hover, #product_nav_custom_overlay.hover').length) return;
		// fade out
		$('#product_nav_custom_overlay').fadeOut(200);
		// ditch the window resize listener
		$(window).unbind('resize', vcb_store.productNavCustomOverlayPosition);
	}
	
	// product nav custom overlay position
	,productNavCustomOverlayPosition: function() {
		// vars
		var offset = $('#product_nav_custom').offset()
			,$overlay = $('#product_nav_custom_overlay');
		// position it
		$overlay.css({ left: offset.left + 'px', top: (offset.top + 10) + 'px' });
	}
	
	// product nav custom overlay show
	,productNavCustomOverlayShow: function() {
		// position
		vcb_store.productNavCustomOverlayPosition();
		// add window listener to position on resize
		$(window).bind('resize', vcb_store.productNavCustomOverlayPosition);
		// and show
		$('#product_nav_custom_overlay').fadeIn(200);
	}
	
};

// get url vars jquery extension, modded from http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
$.extend({
  getUrlVars: function(url_string) {
    var vars = [], hash;
    var hashes = url_string.slice(url_string.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = decodeURI(hash[1]);
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});
