// Title: FJ Flowers - javascript
// Author: Kalon Edser, http://www.kalonedser.com/
// Updated: 6 July 2011

jQuery(document).ready(function() {

	$('body').addClass('js');
	
	$.localScroll();
	$.localScroll.hash();

	// site: preload images/loading feedback
	$.preloadImages('/img/prettyPhoto/light_rounded/sprite.png','/img/prettyPhoto/light_rounded/loader.gif','/img/icons/check_alt_32x32_ie.png');
	var ajax_load = '<p class="more-loading"><img src="/img/prettyPhoto/light_rounded/loader.gif" alt="Loading..." /></p>',
		add_success = '<div class="add-success"><img src="/img/icons/check_alt_32x32_ie.png" alt="Added" /></div>';

	// main nav: hover
	$('#nav li:not(.active) a').hover(
		function () { $(this).css('background-position','0 0').animate({ opacity: 0 }, 100); }, 
		function () { $(this).animate({ opacity: 1 }, 100); }
	);
	// main nav: active
	$('#nav .active a').animate({ opacity: .25 }, 100);
	
	// sub nav: remove active class from active product subcategory parent
	$('ul#products-nav li.active').parents('li.active').removeClass('active');

	// mini cart: set opacity & display msg
	var miniCart = function(){
		$('#mini-cart, #featured').css({ opacity: 0.9 });
		$('#mini-cart').hover(
			function () { $(this).animate({ opacity: 0.95 }, 200); }, 
			function () { $(this).animate({ opacity: 0.9 }, 200); }
		);
		$('#mini-cart .yab-price').append(' each');
		$('.yab-msg').hide().slideDown('slow').delay(3000).slideUp('slow');
	}
	miniCart();

	// site: rounded search box for Safari
	if ($.browser.webkit) {
		var $searchvalue = $('#search-input input').attr('value');
		$('<input type="search" name="q" placeholder="Search" autosave="fjflowers" results="10" size="15" />').attr({ value: $searchvalue }).insertAfter('#search-input p');
		$('#search-input p:eq(0)').remove();
	}
	
	$(".sale-tag").effect("pulsate", { times:5 }, 1500);

	// site: inline picture viewer
	var bindBehaviours = function(scope) {

		$("a[rel^='prettyPhoto']").prettyPhoto({
			animation_speed: 'normal', /* fast/slow/normal */
			slideshow: false, /* false OR interval time in ms */
			autoplay_slideshow: false, /* true/false */
			opacity: 0.5, /* Value between 0 and 1 */
			show_title: false, /* true/false */
			allow_resize: true, /* Resize the photos bigger than viewport. true/false */
			counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
			theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
			modal: false, /* If set to true, only the close button will close the window */
			deeplinking: false, /* Allow prettyPhoto to update the url to enable deeplinking. */
			overlay_gallery: false, /* If set to true, a gallery will overlay the fullscreen image on mouse over */
			keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */
			ie6_fallback: true,
			social_tools: false /* html or false to disable */
		});

	}
	bindBehaviours(this);

	// ajax: product list more information toggle
	$('.more-link').toggle(
		function () { // toggle show
			var $thislink = $(this),
				$container = $thislink.parents('.product-info').find('.more-info'),
				$data = $thislink.attr("href")+'?type=more';
		
			$(ajax_load).insertAfter($container).slideDown('fast');

			// load data
			$container.hide().load($data, function() {
				bindBehaviours(this);
				$container.slideDown('normal').siblings('.more-loading').slideUp('fast',function(){ 
					$(this).remove();
					$.scrollTo($thislink.parents('.product-list'), 800, {margin:true} );
					$thislink.addClass('hide-link').text('hide information');
				});
			});
		},
		function () { // toggle hide
 			$(this).removeClass('hide-link').text('show information').parents('.product-info').find('.more-info').slideUp('normal');
		}
	);

	var ajaxify = function() {
		// ajax: add to cart
		$('.add-cart input.submit').click(function() {
			var $thisButton = $(this),
				$thisVal = $thisButton.attr('name'),
				$thisForm = $thisButton.parents('form'),
				$thisParent = $thisForm.parent('.add-cart'),
				$thisQty = $thisForm.find('input[name=qty]').val(),
				$parentHeight = $thisParent.height(),
				loadUrl = $thisForm.attr('action'),
				loadUrl = loadUrl.substr(0,loadUrl.indexOf('#')),
				dataString = $thisForm.serialize()+'&'+$thisVal+'=1&type=minicart';
	
			$thisParent.fadeTo('normal', 0).after(ajax_load).siblings('.more-loading').addClass('add-loading').height($parentHeight).fadeIn('normal');
			$thisButton.attr('disabled', true);
			$('.yab-msg').stop(true,false).slideUp('slow');

			$.post(loadUrl, dataString, function(result,status){
				if(status == 'success') {
					$('#mini-ajax').html(result);
	
					$(add_success).insertAfter($thisParent).height($parentHeight).append('<p>'+$thisQty+' added</p>').fadeIn('slow', function(){ 
						$thisParent.css('opacity', 1);
						$thisButton.attr('disabled', false);
					}).delay(3000).fadeOut('slow', function(){ $(this).remove(); }).siblings('.more-loading').fadeOut('normal', function(){ $(this).remove(); });

					miniCart();
				} else {
					alert(status);
				}
			}, "html");
			return false;
		});
	}
	
	ajaxify();

	// if ($.browser.msie && $.browser.version <= 6) {
	// 
	// } else {
	// 
	// }

	// ajax: message pane toggle
	var messages = $('#messages');
	$('a[rel^="message"]').toggle(
		function() { // toggle show
			var $thislink = $(this),
		 		content = $thislink.attr("href")+'?type=text';
			
			$thislink.parents('p').append(ajax_load);

			// load data
			messages.hide().load(content, function(){
				messages.slideDown('normal', function(){
					$.scrollTo(messages, 800, {margin:true} );
				});
				$('.more-loading').hide();
			});
		},
		function() { // toggle hide
			messages.slideUp('normal');
		}
	)

	// checkout: switch message textarea field & PayPal icons visibility
	var paypal = 'Purchase via PayPal',
		paypalIcons = '<span class="paypal-icons" title="Pay by credit card with PayPal"></span>';
		
	// checkout: sort payment options
	$('select#payment').sortOptions(false).selectOptions(paypal);
	var $paymentSelect = $('select#payment').val();

	if($paymentSelect == paypal) {
		// checkout: hide message textarea field
		$("p.yab-shop-text").hide();
		$('select#payment').after(paypalIcons);
	}

	$('select#payment').change(function(){
		switch ($(this).val()){
			case paypal:
				$("p.yab-shop-text").hide();
				$(".paypal-icons").show();
			break;
			default:
				$("p.yab-shop-text").show();
				$(".paypal-icons").hide();
		}
	});
	
	// checkout: create states option list
	var $stateVal = $('#yab-checkout-form input#state').val(),
		statesList = Array('','Australian Capital Territory','New South Wales','Northern Territory','Queensland','South Australia','Tasmania','Victoria','Western Australia','Other (International)'),
		$statesForm = $('<select id="state" name="state|r" class="list"></select>');
		
	$.each(statesList, function(key, value) {
		var selValue = value;
		if(selValue == $stateVal) { var selValue = selValue + '" selected="selected'; } 
		$statesForm.append(
			$('<option value="' + selValue + '">' + value + '</option>')
		);
	});

	$('#yab-checkout-form input#state').before($statesForm).remove();

	// site: load after all resources are loaded
	$(window).load(function() {

		// rotate side images
		$('.side-images').cycle({ 
			timeout:  10000, 
			speed:  3000,
			pause: 1
		});

	});

	// site: external links
	$('A[rel="external"]').click( function() {
        window.open( $(this).attr('href') );
        return false;
    });

});
