$(function() { 

/* --------------------------------------------------
   Cufon
--------------------------------------------------- */
	if (!$.browser.msie) {
		Cufon.replace('table tfoot a', { fontFamily: 'Archer Light', hover: true });
		Cufon.replace('.entitled', { fontFamily: 'Archer Light' });
	}
	if (!$.browser.msie || (parseInt($.browser.version) >= 7)) {
		Cufon.set('fontFamily', 'Archer Light')
		.replace('form button')('.button')('#back');
	}
	
	/* Fixed for Cufon */
		$('#loginBar .cartBox a span').css({'margin-bottom': 0 });
		$('.main .wrapper > .change').css({'margin-top': '33px' });

/* --------------------------------------------------
  Galleries and Slideshows
--------------------------------------------------- */	
	/* Slideshow call */
		$('#homepage .half:eq(0) .slideshow').slideshow({speed: '800', delay: '900', pause: '1000' /*, autoSlide: false*/});
		$('#homepage .half:eq(1) .slideshow').slideshow({speed: '800', delay: '1800', pause: '1000' /*, autoSlide: false*/});
		$('#mainPanel').slideshow({speed: '1000'});
		
	/* Product Gallery */
		$('.product .views a').click(function(){
			$(this).parents('.product').find('.image .inner').prepend($('<div />').addClass('loadImg').html('<img src="/images/ico-wait.gif" />').hide().fadeIn('fast'));

			$(this).parents('.product').find('#product-img').attr('src', $(this).attr('href')).load(function(){
				$(this).parents('.product').find('.loadImg').fadeOut('fast', function() { $(this).remove(); });
			});
			return false;
		});


/* --------------------------------------------------
  External websites
--------------------------------------------------- */
	$('.blank').live('click', function(){
		window.open($(this).attr('href'));
		return false;
	});

/* --------------------------------------------------
  PopIn login
--------------------------------------------------- */
	function sendError(url, call, status, error, browser) {
		$.ajax({
			type:	'post',
			url:	'/admin/sendError',
			data:
			{
			  'url'			: url,
			  'call'		: call,
			  'status'		: status,
			  'error'		: error,
			  'browser'		: browser
			},
			error: function(xhr){
				var msg = '<div id="loginBox"><div class="inner">Sorry but there was an error:<br />' + status + " " + error;
				msg += '<p>Please contact the administrator <a href="mailto: admin@mummade.co.nz">admin@mummade.co.nz</a>.';
				msg += '<br /><br />Please copy the details below and paste them into your email:';
				msg += '<br /><code>- url : ' + url;
				msg += '<br />- call : ' + call;
				msg += '<br />- status : '	+ status;
				msg += '<br />- error : ' + error;
				msg += '<br />- browser : ' + browser;
				msg += '<br />- email failure : ' + xhr.status + ' - ' +xhr.statusText;
				msg += '</code>';
				msg += '</div></div>';
				$("#lightbox").html(msg);

			},
			success: function(data){
				var msg = '<div id="loginBox"><div class="inner">Sorry but there was an error:<br />' + xhr.status + " " + xhr.statusText;
				msg += '<p>The administrator has been informed of the problem, please retry later or contact <a href="mailto: admin@mummade.co.nz">admin@mummade.co.nz</a>.</p></div></div>'
				msg += '</div></div>';
				$("#lightbox").html(msg);

			}
		});
	}
	
	function closePopin() {
		$('.formError').remove();
		$('#lightbox').fadeOut(400, function(){ $(this).remove(); });
		$('#overlay').fadeOut(400, function(){ $(this).remove(); });
		if ($.browser.msie && (parseInt($.browser.version) < 7)) {
			$('select').show();
		}
	}

	function createPopin(url, data) {
		$('body').append($('<div />')
							.attr('id', 'overlay')
							.height($('#page').height())
							.click(function(){
								closePopin();
							})
							.hide()
						)
				 .append($('<div />')
				 			.attr('id', 'lightbox')
				 			.load(url, data, function(response, status, xhr) {
								if (status == "error") {
									sendError(document.location.href, url, xhr.status, xhr.statusText, navigator.userAgent + ' ('+$('body').width()+'x'+$('body').height()+')');
								} else {
									$('#lightbox').append($('<a />')
															.attr('href', '#')
															.addClass('close')
															.click(function(){
																closePopin();
																return false;
															})
														)
									if ($.browser.msie && (parseInt($.browser.version) < 7)) {
										$('button > span').addClass('first');
									}

									Cufon.refresh();
									$('#loginBox form').jqTransform();
									$("#outOfStockForm").validationEngine({
										promptPosition: 'topRight',
										unbindEngine : false,
										success : function() {
											$this = $("#outOfStockForm");
											$.ajax({
												type		: "POST",
												cache   : false,
												url     : $this.attr('action'),
												data		: $this.serializeArray(),
												error: function(xhr){
													sendError(document.location.href, $this.attr('action'), xhr.status, xhr.statusText, navigator.userAgent + ' ('+$('body').width()+'x'+$('body').height()+')');

												},
												success: function(data) {
													
													$('#lightbox').html(data);
													Cufon.refresh();
													
												}

											});

											//stay on the page
											return false;

										} // end success validation
									});
								}
				 			})
							.hide()
				 		);
					$('#overlay').fadeIn(500);
					$('#lightbox').fadeIn(700);
					if ($.browser.msie && (parseInt($.browser.version) < 7)) {
						$('select').hide();
						$('html, body').animate({scrollTop:0}, 'slow'); 
					}

	}

	$('#popLogin').click(function(){
		url = $(this).attr('href');
		createPopin(url);
		return false;
	});

  $('.ajaxLoginForm').live('submit', function () {
    $.ajax({
      type: 'POST',
      async: false,
      url: $(this).attr('action'),
      data: $(this).serialize(),
      complete: function (msg) {
        var follow_url = msg.getResponseHeader('X-Follow-Url');
        var error_message = msg.getResponseHeader('X-Error-Message');

        if (msg.status != 200) {
          $.validationEngine.buildPrompt('.errorForm',error_message,'error')
          setTimeout(function() { $('.formError').fadeOut('slow', function(){ $(this).remove(); }); }, 2500);
        }
        else {
          window.location = follow_url;
        }



      }
    });
    return false;

  });

/* --------------------------------------------------
  Subscribe Form
--------------------------------------------------- */

  $('#subscriberForm').live('submit', function () {
    $.ajax({
      type: 'POST',
      url: $(this).attr('action'),
      data: $(this).serialize(),
      dataType: 'json',
      success: function(data) {
        if(data.success) {
          var url = '/sfGuardAuth/subscribe';
          createPopin(url, data);
        }
      }
    });
    return false;
  });

/* --------------------------------------------------
  Basket
--------------------------------------------------- */	
	$('.delete').live('click', function() {
		  $(this).deleteProduct();
		  return false;
	});

	if (!$.browser.msie || (parseInt($.browser.version) >= 7)) {
		$('#loginBar .cartBox').resetCartBox();
		$(window).resize(function() {
			$('#loginBar .cartBox').resetCartBox();
		});
	}

/* --------------------------------------------------
  Forms
--------------------------------------------------- */


/* Reset cartForm */
	function resetCartForm() {
// reset form
		$('#cartForm input[name=quantity]').val(1);
		$("#cartForm .footer .price").html('$' + $("#cartForm input[name=product-price]").val());
		$('#cartForm input:radio:checked').removeAttr('checked');
		$('#cartForm label.checked').removeClass('checked');
		$('#cartForm select option:selected').removeAttr('selected');
// jqTransform for select
		if ((!$.browser.opera)&&(!$.browser.msie || $.browser.version.substr(0,1) > 7)) {
			$('#cartForm select').each(function(){
				var value = $('option', this).eq(0).html();
				$('option', this).eq(0).attr('selected', 'selected');
				$(this).parents('.jqTransformSelectWrapper')
				.find('span')
				.html(value);
				$('#cartFormUlSelect li a').removeClass('selected');
				$('#cartFormUlSelect li').eq(0).find('a').addClass('selected');
			});
		}
	}

	/* Reset cartForm submit button */
	function resetSubmitCartFormButton() {
		$('#cartForm .footer button')
			.removeAttr('disabled')
			.removeAttr('style')
			.delay(2000).html('<span><span class="color">add</span> to basket</span>');
		if ($.browser.msie && (parseInt($.browser.version) < 7)) {
			$('button > span').addClass('first');
		}
		Cufon.refresh('form button');
	}

	/* CartForm Colour Selection */
		$('#color :checked').each(function(){
			$(this).parent().find('label').addClass('checked');
			$('#colorTarget').html($(this).parent().find('img').attr('alt'));
			Cufon.refresh('.title');
		});
	
		$('#color label').hover(function(){
			$('#colorTarget').html($(this).find('img').attr('alt'));
			Cufon.refresh('.title');
		}, function(){
			if(!$('#color .checked').length) {
				$('#colorTarget').html('(select below)');		
			} else {
				$('#colorTarget').html($('#color .checked').find('img').attr('alt'));
			}
			Cufon.refresh('.title');
		});

		$('#color label').live('click', function () {
      $('#color .checked').removeClass('checked');
      $(this).addClass('checked');
	    	
			$('#colorTarget').html($(this).find('img').attr('alt'));
			Cufon.refresh('.title');

	 });

   $('#cartForm #size').live('change', function() {
    if( $('#cartForm input[name=colour_id]:radio:checked').val() ) {
      var data = {
        'product_id' : $('#cartForm input[name=product_id]').val(),
        'quantity' : $('#cartForm input[name=quantity]').val(),
        'size_id' : $(this).val(),
        'colour_id' : $('#cartForm input[name=colour_id]:radio:checked').val()
      };
      getQuantityAvailableForVariant(data);
    }
   });

  function getQuantityAvailableForVariant(data)
  {
    $("#qtyBox").fadeOut("fast");
    $.ajax({
      type	: "POST",
      cache   : false,
      url     : '/product/getQuantityAvailableForVariant',
      data	: data,
      dataType: 'json',
      error: function(xhr){
        sendError(document.location.href, '/product/getQuantityAvailableForVariant', xhr.status, xhr.statusText, navigator.userAgent + ' ('+$('body').width()+'x'+$('body').height()+')');
      },
      success: function(data) {
        if(data.success){
          $('#qty-available').html(data.quantity);
          $('#qty-description').html(data.description);
        }
      }
    });
    $("#qtyBox").fadeIn("fast");
  }

	  	$('#color label img').live('click', function () {
	  		$(this).parent().trigger('click');

        var data = {
          'product_id' : $('#cartForm input[name=product_id]').val(),
          'quantity' : $('#cartForm input[name=quantity]').val(),
          'size_id' : $('#cartForm #size').val(),
          'colour_id' : $(this).parent().parent().find('input[name=colour_id]').val()
        };

        getQuantityAvailableForVariant(data);

	  	});
		
	/* JqTransform */
		$('form').not('#cartForm').jqTransform();
		$('input:checkbox').display();
		
		$('#cartForm').jqTransform({radio: false, checkbox: false});
	
	/* update price */
	$("#cartForm input[name=quantity]").change(function(){
		$("#cartForm .footer .price").html('$' + ($(this).val() * $("#cartForm input[name=product-price]").val()).toFixed(2));
	});
	$("#cartForm input[name=quantity]").keyup(function(){ $(this).trigger('change'); })
	
	/* Validation */
		$('#deliveryForm').validationEngine({promptPosition: 'topRight'});

    $('#registerForm').validationEngine({promptPosition: 'topRight'});

    $('#subscriberForm').validationEngine();
    
    $('#standardForm').validationEngine({promptPosition: 'topRight'});


		$("#cartForm").validationEngine({
			promptPosition: 'topRight',
			unbindEngine : false,
			success : function() { 
				// loader
				$('#cartForm .footer button')
					.attr('disabled', 'disabled')
					.css({'cursor':'wait'})
					.html('<span><span class="color wait">adding</span></span>');
				$('.nbItems').html('<img src="/images/ico-wait-white.gif" />');
				if ($.browser.msie && (parseInt($.browser.version) < 7)) {
					$('button > span').addClass('first');
				}
				Cufon.refresh('form button');

        var product_id = $('#cartForm input[name=product_id]').val();
        var quantity = $('#cartForm input[name=quantity]').val();
        var size_id = $('#cartForm #size').val();
        if ($('#cartForm input[name=colour_id]').attr('type') == 'hidden') {
         var colour_id = $('#cartForm input[name=colour_id]').val();
        } else {
         var colour_id = $('#cartForm input[name=colour_id]:radio:checked').val();
        }
        //var colour_id = $('#cartForm input[name=colour_id]:radio:checked').val();
				
				//send the ajax request
				//$.post($(this).attr('action'),
				$.post('/cart/addToCart',
					{	
					  'product_id'	: product_id,
					  'quantity'	: quantity,
					  'size_id'		: size_id,
					  'colour_id'	: colour_id
					},	
				    function(data){
				    	if(data['status'] == 'success') {
						// Buttons update
						/*
					  		$('#cartForm .footer').append($('<p />')
					  			.addClass('valid')
					  			.html('added')
					  			.hide()
					  			.fadeIn(1000, function() {
					  			})
					  			.delay(1500)
					  			.fadeOut(1000, function() { $(this).remove(); })
					  		);
								*/
						   $('#cartForm .footer button')
								.removeAttr('disabled')
								.removeAttr('style')
								.delay(2000).html('<span><span class="valid">added</span></span>');
							if ($.browser.msie && (parseInt($.browser.version) < 7)) {
								$('button > span').addClass('first');
							}
							Cufon.refresh('form button');

						// Cart box update
							  $('.nbItems').load('/cart/getCartQuantity');
									
						// reset submit button
							setTimeout( function() { resetSubmitCartFormButton(); }, 2000);
						// reset form
							resetCartForm();

                // end success ajax
						} else {
							var url = '/product/outOfStockForm';
							  var data = {
								product_id: product_id,
								colour_id:  colour_id,
								size_id:  size_id,
								quantity: quantity
							  };
							createPopin(url, data);

						// reset submit button
						// reset form
						 $('.nbItems').load('/cart/getCartQuantity');
							setTimeout( function() { resetSubmitCartFormButton(); resetCartForm(); }, 1000);
						}

				});
				
			    //stay on the page
			  	return false;		
					
			} // end success validation
		});

	/* Basket - Validation / Shipping / Update total */	
		
		$('#basket .qtt input').each(function(){
			$(this).removeAttr('readonly');
			$(this).attr('rel', $(this).val());
		});
		$('#basket .qtt input').change(function(){
			var $obj = $(this);
			if(!isInteger($obj.val())) {
				$obj.val($obj.attr('rel'));
			} else {
				$.post('/cart/updateQuantity',
					{
						'id'  : $obj.attr('id').replace('id',''),
						'qty' : $obj.val()
					},
					function(data){
						if(data.success) {
							$obj.parents('tr').find('.total').html('$'+data.item_total)
							$obj.parents('table').find('#subtotal').html('$'+data.subtotal)
							$obj.parents('table').find('#shippingtotal').html('$'+data.shipping_total)
							$obj.parents('table').find('#total').html('$'+data.total)
							$('.nbItems').load('/cart/getCartQuantity');
							$obj.attr('rel', data.quantity);
						}
						else
						{
						//  $obj.val($obj.attr('rel'));
						  var url = '/product/outOfStockForm';
						  var data = {
							item_id: $obj.attr('id').replace('id',''),
							'quantity' : $obj.val()
						  };
						  createPopin(url, data);
						  $obj.val($obj.attr('rel'));
						}
					},
					'json'
				);

        //$(this).attr('rel', $(this).val());
			}
			
		});
		$("#basket .qtt input").keyup(function(){
			var $obj = $(this);
			if ($obj.val() == 0) {
				$(this).blur();
				$obj.parents('tr').animate({'opacity': '0.5'}, 700);
				$('body').append($('<div />').attr('id', 'confirmBox')
											 .css({
												 'position' : 'absolute',
												 'top' : $obj.parents('tr').offset().top + 20,
												 'left' : $obj.parents('tr').offset().left + 150
											 })
											 .html('This action will delete this item from your cart.<br />Confirm?')
											 .append($('<a />').addClass('archer')
															   .html('yes')
															   .click(function(){
																  $obj.deleteProduct();
																  $(this).parent().fadeOut(200, function() { $(this).remove(); })
															   })
											 )
											 .append($('<a />').addClass('archer')
															   .html('no')
															   .click(function(){
																  $(this).parent().fadeOut(200, function() { $(this).remove(); })
																  $obj.val($obj.attr('rel'));
																  $obj.parents('tr').animate({'opacity': '1'}, 700);
															   })
											 )
											 .hide()
											 .fadeIn('slow')
								);
				Cufon.refresh('#confirmBox a');
			} else {
				$(this).trigger('change');
			}
		});
		if ($('#basket table #shippingCell').length == 0) {
			$('#basket tfoot tr:eq(0)').after($('<tr />').attr('id', 'shippingCell')
														.html('<td colspan="2"><span id="shippingText"><a href="#">Calculate shipping &amp; handling</a></span></td>')
											);
					   						Cufon.refresh('table tfoot a');
		}
		$('#shippingText a').live('click', function(){			
			$('#shippingCell')
				.html($('<td />')
					.attr('colspan', '2')
					.html('<img src="/images/ico-wait.gif" alt="please wait" style="float: right" />')
					.load('/cart/calculateShippingForm', function() {
						Cufon.refresh();
						$('#shipping').jqTransform();
							
						$("#shipping").validationEngine({
							promptPosition: 'topRight',
							unbindEngine : false,
							success : function() { 	
							
							//send the ajax request
								$.post('/cart/calculateShippingForm',
									{
									  'region_id'		: $('#shipping select[name=region_id]').val(),
									  'is_rural'		: $('#shipping input[name=is_rural]:radio:checked').val()
									},	
								    function(data){													    
								    	if(data && data.success) {
											$('#shippingCell').html('')
															  .append($('<td />').html('<span id="shippingText">' + data.region + ' <br /><a href="#"><span class="small">(change)</span></a></span>'))
															  .append($('<td />').html('<span id="shippingtotal">$'+data.shipping_total+'</span>'));
					   						$('#total').html('$'+data.total)					    					   						
					   						Cufon.refresh('table tfoot a');
										}														  		
									  	
									}, // end success ajax	
									'json'
								); // end ajax
								return false;	
							} // end validation success
						}); // end validation
					}) // end load()
				);	// end html()			
			return false;
		});

	/* Pre-address fill form */
	$('.preAddressing').live('change', function(){
		$val	= $(this).val();
		$formID	= $(this).parents('form').attr('id');
		$fieldset	= $(this).parents('fieldset');
		$checkbox = $('input#deliveryAddress_is_rural[type=checkbox]', $fieldset);
		$select = $('select', $fieldset).eq(1);

		if($val == 'null') {
		/* reset form */
			$('input[type=text]', $fieldset).val('');
			$checkbox.removeAttr('checked');
			if($checkbox.parent().find('a.jqTransformChecked').length) {
				$checkbox.parent().find('a.jqTransformChecked').removeClass('jqTransformChecked');
			}

			$('option:selected', $select).removeAttr('selected');
			$option = $('option', $select).eq(0);
			$option.attr('selected', 'selected');

			if ($select.parents('.jqTransformSelectWrapper').length) {
				var index = $('select').index($select);
				$select.parents('.jqTransformSelectWrapper').find('span').html($option.html());
				$ul = $('.jqTransformSelectUl').eq(index);
				$('li a', $ul).removeClass('selected');
				$('li', $ul).eq(0).find('a').addClass('selected');
			}
		} else {
			$.ajax({
				type	: "POST",
				cache   : false,
				url     : '/user/getAddress',
				data	: { 'id' : $val},
				dataType: 'json',
				error: function(xhr){
					sendError(document.location.href, '/user/getAddress', xhr.status, xhr.statusText, navigator.userAgent + ' ('+$('body').width()+'x'+$('body').height()+')');
				},
				success: function(data) {
					if(data.success){
						$('input[type=text]', $fieldset).eq(0).val(data.name);
						$('input[type=text]', $fieldset).eq(1).val(data.address1);
						$('input[type=text]', $fieldset).eq(2).val(data.address2);
						$('input[type=text]', $fieldset).eq(3).val(data.suburb);
						$('input[type=text]', $fieldset).eq(4).val(data.city);
						$('input[type=text]', $fieldset).eq(5).val(data.postcode);
						$('input[type=text]', $fieldset).eq(6).val(data.phonenumber);

						if(data.is_rural) {
							$checkbox.attr('checked', 'checked');
						} else {
							$checkbox.removeAttr('checked');
						}
						if($checkbox.parent('.jqTransformCheckboxWrapper').length) {
							if(data.is_rural) {
								$checkbox.parent().find('a.jqTransformCheckbox').addClass('jqTransformChecked');
							} else {
								$checkbox.parent().find('a.jqTransformCheckbox').removeClass('jqTransformChecked');
							}
						}

						$('option:selected', $select).removeAttr('selected');
						$option = $('option[value='+data.region_id+']', $select);
						$option.attr('selected', 'selected');

						if ($select.parents('.jqTransformSelectWrapper').length) {
							var index		= $('select').index($select);
							var indexOpt	= $('option', $select).index($option);
							$select.parents('.jqTransformSelectWrapper').find('span').html($option.html());
							$ul = $('.jqTransformSelectUl').eq(index);
							$('li a', $ul).removeClass('selected');
							$('li', $ul).eq(indexOpt).find('a').addClass('selected');
						}
					}
				}
			});
		}
	});

	/* Login lightbox */
	$('#popInTransform').lightbox();

	/* Change address lightbox */
	$('.changeAddress').updAdd();
	
/* --------------------------------------------------
   Browsers Hacks
--------------------------------------------------- */
	/* IE 6 */
	if ($.browser.msie && (parseInt($.browser.version) < 7)) {

		$('.main .wrapper > .change').css({ 'float': 'left' });
		$('button > span').addClass('first');
		$('.button > span').addClass('first');
	}
	
	/* IE 7 */
	if ($.browser.msie && (parseInt($.browser.version) == 7)) {		
		$('form button').css({'height': '38px'});
		$('.views li').each(function(){
			$(this).hover(function(){
				$(this).css({'z-index': 2000 });
			},
			function(){
				$index = $('.views li').index($(this));
				$(this).css({'z-index': 1000 - ($index *100) });
			});
		});
		
	}

	function isInteger(obj) {
		var reg = /^[0-9]+$/;
		return reg.exec(obj);
	}
	
});
