// JavaScript Document

(function ($) {
// VERTICALLY ALIGN FUNCTION
$.fn.vAlign = function() {
  return this.each(function(i){
  var ah = $(this).height();
	var ph = $(this).parent().height();
  var mh = (ph - ah) / 2;
  if(mh>0) {
    $(this).css('margin-top', mh);
  } else {
    $(this).css('margin-top', 0);
  }
});
};
})(jQuery);

// DEFAULT INPUT TEXT FUNCTION
function defaultInputText()
{
	$(".defaultText").focus(function(srcc)
	{
		if ($(this).val() == $(this)[0].title)
		{
			$(this).removeClass("defaultTextActive");
			$(this).val("");
		}
	});
	
	$(".defaultText").blur(function()
	{
		if ($(this).val() == "")
		{
			$(this).addClass("defaultTextActive");
			$(this).val($(this)[0].title);
		}
	});
	
	$(".defaultText").blur();  
}

// ROUND CORNERS
function roundCorners()
{
	if ($('#registration_teaser_form').length )
	{
		$('#registration_teaser_form').corner('5px');
	}
}

// USE FANCYBOX TO HANDLE ALL ERROR MESSAGES
function showErrorMessage(message)
	{
		$.fancybox(
			'<div class="mw">'+message+'</div>',
			{
				'autoDimensions' : false,
				'width'	: 450,
				'height' : 'auto',
				'padding': 3,
				'showCloseButton': true,
				'overlayColor': '#333'
			});
	}
	
// REGISTRATION TEASER FORM
function register_teaser()
{
	$('#registration_teaser_form').submit(function(event)
   	{
		event.preventDefault();
		
		$.post('/resources/actions/register-tease.php',
			   {
				   email: $('[name=email]').val()
				   },
				function(data) {
					if(data.success)
					{									
						window.location = $('#registration_teaser_form').attr('action') + "?email=" + $('[name=email]').val();
					} else {						
						showErrorMessage(data.message);
					}
				}, 'json');
		return false;
				   
   	});
}

function change_captcha()
	 {
	 	document.getElementById('captcha').src="/resources/captcha/get_captcha.php?rnd=" + Math.random();
	 }

// REGISTRATION FORM
function register()
{
	if ( $("#registration_form select").length )
	{
		$("#registration_form select").selectbox();
	}
	
	$('img#refresh').click(function() {  
			change_captcha();
	 });
	
	$('#registration_form').submit(function(event) 
	{
		event.preventDefault();
		
		var agreement = 0;
		var optout_shopwise_option = 0;
		var optout_ourdeal_option = 0;
		if ($('[name=terms]').is(':checked')) 
		{
			agreement = 1;
		}
		if ($('[name=optout_shopwise]').is(':checked')) 
		{
			optout_shopwise_option = 1;
		}
		if ($('[name=optout_ourdeal]').is(':checked')) 
		{
			optout_ourdeal_option = 1;
		}
		
		$.post('/resources/actions/register.php',
			  {			
				firstname: $('[name=firstname]').val(),
				lastname: $('[name=lastname]').val(),
				//address_line1: $('[name=address_line1]').val(),
				//address_line2: $('[name=address_line2]').val(),
				//suburb: $('[name=suburb]').val(),
				state: $('[name=state]').val(),
				postcode: $('[name=postcode]').val(),
				mobile: $('[name=mobile]').val(),
				email: $('[name=email]').val(),
				//phone_pt1: $('[name=phone_pt1]').val(),
				//phone_pt2: $('[name=phone_pt2]').val(),
				your_centre: $('[name=your_centre]').val(),
				code: $('[name=code]').val(),
				terms: agreement,
				optout_shopwise: optout_shopwise_option,
				optout_ourdeal: optout_ourdeal_option
			},
				function(data) {
					if(data.success)
					{					
						$('#reg_thanks').slideDown();
						$(':input','#registration_form')
							 .not(':button, :submit, :reset, :hidden')
							 .val('')
							 .removeAttr('checked')
							 .removeAttr('selected');
						
					} else {						
						showErrorMessage(data.message);
					}
				}, 'json');
		return false;

	});
	
	
	
		$("#terms-cond a").fancybox({
				'hideOnContentClick': false,
				'autoDimensions': false,
				'width': 700,
				'height': 500,
				'scrolling': 'no',
				'padding': 6,
				'overlayShow': true,
				'showCloseButton' : true
			});
	
}

function link_to_centre()
{
	if ( $('#external_link').length )
	{
		$('#centre_id').selectbox({
								  onChange: function(val, inst)
								  {
									window.open( val );
								  }
								  });
	}
}

function show_centre_products()
{
	var targetURL = $("#centre_id option:selected").val();
	if (targetURL != 0)
	{
		pathArray = window.location.pathname.split( '/' );
		var newLocation = '/'+pathArray[1] + '/' + targetURL  + '/';
		window.location = newLocation;	
	}
}

function giftwise_magnify()
{
	if ( $('.pr_thumb').length )
	{
			$('a[rel="popup"]').colorbox({'current': '', 'initialWidth': 500, 'initialHeight': 500 }) ;
	}
	
	if ( $('#centre_selection.centre_products_area').length )
	{
		$('#centre_selection #centre_id').selectbox();
	}
			
	/* this will take care of the Gift List */
	if ( $('#gifts').length )
	{
		var gift_ids = new Array();
		for (i=1; i<=20; i++)
		{
			gift_ids.push("#gifts #products li.row"+i+" .product_item");
		}
		resizeItems(gift_ids);
		//console.log('resize gifts');
	}
	
	if ( $('#products ul.page_1').length )
	{
		var gift_ids = new Array();
		/*
		for (i=1; i<=20; i++)
		{
			gift_ids.push(	"#products ul.page_"+i+" li.row1 .product_item",
							"#products ul.page_"+i+" li.row2 .product_item",
							"#products ul.page_"+i+" li.row3 .product_item");
		}
		*/
		gift_ids.push(	"#products li.row1 .product_item",
							"#products li.row2 .product_item",
							"#products li.row3 .product_item");
		resizeItems(gift_ids);
		
		var gift_containers = new Array();
		for (i=1; i<=20; i++)
		{
			gift_containers.push("#products ul.page_"+i);
		}
			resizeItems(gift_containers);
	}
	
}

function giftwise_adding()
{
	if ( $('#products .add_to').length )
	{
		
		var article_ids = new Array("#products li.row1 .product_item",
								"#products li.row2 .product_item",
								"#products li.row3 .product_item");
		resizeItems(article_ids);
		
		
		$('#products .add_to a').unbind('click').bind('click',function() {
			
			var product_id = $(this).attr('id').split('_')[1];
			
			$.post('/resources/actions/gift_list.php',
			  {			
				product_id: product_id,
				enter_type: 'add'
			},
				function(data) {
					if(data.success)
					{					
						giftwise_counter(product_id, 'add');			
					} 
				}, 'json');
			return false;
			
			});
		
	}
	
	if ( $('#products .remove_from').length )
	{
		$('#products .remove_from a').unbind('click').bind('click',function() {
			
			var product_id = $(this).attr('id').split('_')[1];
			
			$.post('/resources/actions/gift_list.php',
			  {			
				product_id: product_id,
				enter_type: 'remove'
			},
				function(data) {
					if(data.success)
					{					
						giftwise_counter(product_id, 'remove');			
					} 
				}, 'json');
			return false;
			
			});
		
	}
}

function giftwise_counter(product_id, enterType)
{
	var mycount = $('#item_count span').html();
	if (enterType == 'add')
	{
		mycount = parseInt(mycount) + 1;
	}
	else
	{
		mycount = parseInt(mycount) - 1;
	}
	$('#item_count span').html( mycount );
	if ( $('#r_'+product_id).length )
	{
		$('#r_'+product_id).remove();
	}
	else
	{
		changeGiftListButton(product_id, enterType);
	}
	giftwise_adding();
}

function changeGiftListButton(product_id, action)
{
	var myButton = '#p_' + product_id;
	
	if (action == 'add')
	{
		//console.log(myButton);
		$(myButton).parent().removeClass('add_to').addClass('remove_from');
		$(myButton + ' span').html('Remove from gift list');
	}
	else if (action == 'remove')
	{
		
		$(myButton).parent().removeClass('remove_from').addClass('add_to');
		$(myButton + ' span').html('Add to gift list');
	}
}

function audioManager()
{
	
	if ($('.audio_placeholder').length)
	{
		$('.audio_placeholder div span').vAlign();
	}
	
	if ($('#audio').length )
	{
		var article_ids = new Array("#audio li.audiorow_1 .description",
								"#audio li.audiorow_2 .description",
								"#audio li.audiorow_3 .description");
		resizeItems(article_ids);
		
		$('#audio li.btn_play a:not([target])').unbind('click').bind('click',function(e) {
			
			var mydesc = $(this).closest('li[class^="audiorow_"]').find('.description').text();
			var mysrc = $(this).attr('href');
			
			$(".jp-title li").html('Current stream: <strong>'+mydesc+'</strong>');
			
			$("#jquery_jplayer_1").jPlayer("stop");
			
			$("#jquery_jplayer_1").jPlayer("setMedia", {
					mp3: $(this).attr('href')
			  }).jPlayer("play");
			
			audioManager();
															   
		   	e.preventDefault();
			
		 });
	}
}

	
/***********************************************
************ ARTICLES EQUAL HEIGHT *************
************************************************/ 

function resizeItems(article_ids)
{
	var articles_types = article_ids.length;
	
	for ( i=0; i<articles_types; i++ )
	{
		// check to see if the specified element(s) exists
		if ($(article_ids[i]).length)
		{
			//console.log(article_ids[i] + ' resized');
			// and if any of them do does, resize!
			$(article_ids[i]).equalHeightColumns();
		}
	}
	
}


/***********************************************
************ HTML5 YOUTUBE HANDLER *************
************************************************/ 

function youtubeHTML5picker()
{
	if 	($('#yt_iframe').length )
	{
		
		
		//var maxHeight = $('#ytplayer_div2 .vid_thumbs a:first ').height();
		//var myWidth = $('#products ul:first').width();
		
		
		$(".myController").jFlow({
			slides: "#yt_thumbs_slider",
			controller: ".jFlowControl", // must be class, use . sign
			//slideWrapper : "#products ul", // must be id, use # sign
			//selectedWrapper: "jFlowSelected",  // just pure text, no sign
			auto: false,		//auto change slide, default true
			width: "456px",
			height: "96px",
			duration: 400,
			prev: ".jFlowPrev", // must be class, use . sign
			next: ".jFlowNext" // must be class, use . sign
		});
		
		
		$('#ytplayer_div2 a').unbind('click').bind('click',function(e) {

			var youtube_id = $(this).attr('rel');
			var youtube_title = $(this).find('img').attr('title');
			//console.log(youtube_title);
			//alert(youtube_id);
			if (youtube_id != '' && youtube_id != undefined)
			{
				var new_video = '<iframe class="youtube-player" type="text/html" width="452" height="344" src="http://www.youtube.com/embed/' + youtube_id + '?rel=0" frameborder="0"></iframe>';
				$('#yt_iframe').empty().html(new_video);
				$('#vox_pops h2').text(youtube_title);
			}
			return false;
			});
	}
}

/***********************************************
************ FACBOOK SHARE BUTTON **************
************************************************/ 

function facebook_share()
{
	if ($('.facebook_share a').length )
	{
		//console.log('fb');
		
		$('.facebook_share a').click(function() {
				//console.log('facebook_share');
				FB.ui(
				  {
					method: 'feed',
					name: $('meta[property="og:site_name"]').attr('content'),
					link: $('meta[property="og:url"]').attr('content'),
					picture: $('meta[property="og:image"]').attr('content'),
					caption: $('meta[property="og:title"]').attr('content'),
					description: $('meta[name="description"]').attr('content')
				  },
				  function(response) {
					if (response && response.post_id) {
					  //alert('Post was published.');
					  _gaq.push(['_trackEvent', 'links', 'facebook', 'share on facebook']);
					  
					} else {
					  //alert('Post was not published.');
					}
				  }
				);
		 });
		
	}
}


/***********************************************
********** GIFTWISE PRODUCTS CONTROL ***********
************************************************/ 


function products_controls()
{
	if ($('#gift_slide #products ul li.row1').length )
	{
		
		
		var maxHeight = $('#products ul:first').height();
		var myWidth = $('#products ul:first').width();
		
		
		$(".myController").jFlow({
			slides: "#products",
			controller: ".jFlowControl", // must be class, use . sign
			//slideWrapper : "#products ul", // must be id, use # sign
			//selectedWrapper: "jFlowSelected",  // just pure text, no sign
			auto: false,		//auto change slide, default true
			width: myWidth + "px",
			height: maxHeight + "px",
			duration: 400,
			prev: ".jFlowPrev", // must be class, use . sign
			next: ".jFlowNext" // must be class, use . sign
		});
		
		
		$('.myController span').click( function() {
		 giftwise_magnify();
		});
		
		
	}
}


$(function() {

	defaultInputText();
	
	$('ul#nav a span').vAlign();
	$('ul#giftwise_categories a span').vAlign();
	
	register_teaser();
	register();
	roundCorners();
	giftwise_magnify();
	giftwise_adding();
	audioManager();	
	link_to_centre();
	youtubeHTML5picker();
	facebook_share();
	products_controls();
	
	$(".centre_products_area #centre_id").change(show_centre_products);
	
	if ( $('.column_of_four').length )
	{
		resizeItems($('.column_of_four'));
	}
		
});
