$(document).ready(function(){
	
	Site.init();
	
});

var Site = {
	
	init:function(sliderSettings) {
		
		//HANDLE EXTERNAL LINKS
		Site.externalLinks();
				
		//MEMBER LOGIN
		if($('#member-login').length != 0) {
			Site.memberLogin();
		}
	
		//SEARCH
		if($('#search').length != 0) {
			Site.search();
		}
		
		//FEATURE SLIDER
		if($('#feature-home').length != 0) {
			Site.featureFader();
			Site.providerSlider();
		}
		
				
		//TEXT RESIZZLE
		if($('#usability-elements').length != 0) {
			$('#primary').textResizzle();	
		}
		
		//PRINT
		if($('#usability-elements').length != 0) {
			Site.print();
		}
		
		//IMAGE GALLERY
		if($('.image-gallery').length != 0) {
			Site.fancyBoxInit();
			$('#image-gallery li:nth-child(5n)').addClass('nth-child-fifth');
		}
		
		// FORM DATE PICKER
		if ($('.datePicker').length != 0){
			Site.datePicker();
		}
		
		//FORM VALIDATION
		if($('.validate-form').length != 0){
			$('.validate-form').validate();
		}
		
		// School Add/Edit Form
		if($('#form_school_edit').length != 0){
			Site.schoolEditForm();
		}
		
		// Payment Form - Payment Type - Credit/Direct Deposit
		if($('#payment-type-options').length != 0){
			Site.paymentTypes();
		}
		
		// SUBMIT WHEN CHANGE LETTER ON THE SCHOOL LISTING IN THE ADMIN SECTION 
		if($('#form_between').length != 0){
			$('#form_between select').change(function() {
				if($('#select_start').attr('value') != '0' && $('#select_end').attr('value') != '0') {
					$('#form_between').submit();
				}
			});
		}
		
		// SUBMIT WHEN CHANGE USER TYPE ON THE USER LISTING IN THE ADMIN SECTION 
		if($('#form_filter_user').length != 0){
			$('#form_filter_user select').change(function() {
				if($('#select_type').attr('value') != '0') {
					$('#form_filter_user').submit();
				}
			});
		}
		
		
		// CHANGE AMOUNT WHEN CHANGE THE PRODUCT QUANTITY
		if($('.select_qty').length != 0){
			
				$('.select_qty').change(function (){
					// Change set order total to 0
					order_total = 0;		
					
					$('.select_qty').each(function() {
						// Grab the product id and find the price 
						var qty_array = $(this).attr('id').split('_');
						
						// Set the new order total
						order_total = eval(order_total) + $('#price_'+qty_array[1]).html() * this.value;
						$('#amount_total').html(order_total);
				});
				
			});
			
			
		}
		
		// CHANGE AMOUNT WHEN CHANGE THE TICKET QUANTITY
		if($('#ticket_qty').length != 0){
			$('#ticket_qty').change(function (){
				$('#amount_total_event').empty();
				$('#amount_total_event').html($('#amount_per_ticket').html() * this.value);
			});
		}

		
		// SCHOOL DIRECTORY TABS 
		if($('#school-results-tabs').length != 0){
			$( "#school-results-tabs" ).tabs();
		}
		
		
		Site.combobox();
		
		//HOMEPAGE SLIDER
		if($('#image-slide').length != 0) {
			Site.featureSlide();
		}
		
		Site.cycleFader();
		
		//Site.featureWords();
		Site.featureWordParalax();
		
		// SUBSCRIPTION FORM VALIDATION
		if($('#subscription-form').length != 0) {
			$('#subscription-form').validate({			
				rules: {
					user_password: "required",
					user_password_check: {
						equalTo: "#user_password"
					}
				}
			});
		}
		
			
		
		// EVENT REGISTRATION FORM FRONTEND
		if($('#add-delegate').length > 0) {
			
			
			// Setup var i
			if($('.new-delegate').length > 0) {
				var i = $('.new-delegate').length;
				i++;
			} else {
				var i = 1;	
			}
			
			$('.delete-delegate').hover(
				function() {
					$(this).parent('div').css('background-color','#e4eceb');
				},
				function() {
					$(this).parent('div').attr('style','');
				}
			);
			
			// Setup the maximum of delegates
			// var max_delegate = $('#max-delegate').html();
			
			// Hide add button if reached maximum 
			// if($('.new-delegate').length+1 >= max_delegate) {
				// $('#add-delegate').hide();
			// }
			
			
			$('#add-delegate').click(function (){
					
				// Clone delegate block
				$('#delegate').clone(true).appendTo('#delegate-container').attr('id','new-delegate-'+i).attr('class','new-delegate');
				
				$('#new-delegate-'+i).find('input[type="text"]').attr('value','');
				$('#new-delegate-'+i).find('input[type="checkbox"]').removeAttr('checked');
				//$('#new-delegate-'+i).find('input').rules('error valid').;
				$('#new-delegate-'+i).find('input').removeClass('error valid');
				$('#new-delegate-'+i).find('input').next('label').remove();
				
				// Id Re-incrementation
				$('#new-delegate-'+i).find('input').each(function(id, elem) {
					$(this).attr('id',$(this).attr('id')+'_'+i);
					name = $(this).attr('name').replace('[0]','['+i+']');
					$(this).attr('name',name);
				});
				
				i++;

				// if($('.new-delegate').length+1 >= max_delegate) {
					// $('#add-delegate').hide();
				// }
				
			});
			
			$('.delete-delegate').click(function() {
				
				parent = $(this).parent();
				
				$( "#dialog-confirm" ).dialog({
					resizable: false,
					height:180,
					modal: true,
					buttons: {
						"Delete this delegate": function() {
							$( this ).dialog( "close" );
							parent.remove();
							i--;
							// if($('.new-delegate').length+1 < max_delegate ) {
								// $('#add-delegate').show();
							// }
						},
						Cancel: function() {
							$( this ).dialog( "close" );
						}
					}
				});
				
				
			})
		}
		
		
		// ADMIN GENERATE FORM AND FIELDS
		
		if($( "#field_type" ).length > 0) {
			
			function changeFieldForm() {
				
				if($("#field_type").val() == 'Price' || $("#field_type").val() == 'Discount') {
					
					$('#div-required').hide();
					$('#div-place').hide();
	
					$('#div-price').show();
					$('#div-member-price').show();
					$('#div-date').show();
					
				
				} 
				else if($("#field_type").val() == 'Optional') {
					
					$('#div-required').hide();
					$('#div-date').hide();
					
					$('#div-price').show();
					$('#div-member-price').show();
					$('#div-place').show();
					
				}
				
				else if($("#field_type").val() == 'Text' || $("#field_type").val() == 'Checkbox') {
					
					$('#div-price').hide();
					$('#div-member-price').hide();
					$('#div-date').hide();
					
					$('#div-required').show();
					$('#div-place').show();
				}
				else if($("#field_type").val() == 'Label') {
					
					$('#div-price').hide();
					$('#div-member-price').hide();
					$('#div-date').hide();
					$('#div-required').hide();
					
					$('#div-place').show();
				}
			}
			
			changeFieldForm();
			
			$( "#field_type" ).change(function() {
				changeFieldForm();
			});
		}
				
		if($( "#field_date_upto" ).length > 0) {
			$( "#field_date_upto" ).datepicker({ dateFormat: 'dd-mm-yy' });
		}
		
		if($( "#field_date_after" ).length > 0) {
			$( "#field_date_after" ).datepicker({ dateFormat: 'dd-mm-yy' });
		}
		if($( "#subscription_date" ).length > 0) {
			$( "#subscription_date" ).datepicker({ dateFormat: 'dd-mm-yy' });
		}
		
		if($('.delete-item').length > 0) {
			$('.delete-item').click(function() {
				
				url = $(this).attr('href');
				
				$( "#dialog-confirm" ).dialog({
					resizable: false,
					height:180,
					modal: true,
					buttons: {
						"Delete this item": function() {
							$( this ).dialog( "close" );
							window.location = url;
						},
						Cancel: function() {
							$( this ).dialog( "close" );
						}
					}
				});
				return false;
			});
		}
		
		
		// Add/Edit Category
		if( $('#page-id-container').length > 0) {
			
			if ( $('#btn-add-page-id').length > 0 ){

				$('#btn-add-page-id').click( function (){
					Site.pageIdRowAdd();
				} );
				
			}

			Site.pageIdRowRefresh();
		}
		
		// Product Order/Event Registration send invoice popup
		if ( $('#send-invoice').length && $('#status-submit').length ){
			$('#status-submit').click(function(){
				Site.orderSendInvoice();
			});
		}
		
		if ( $('#subscription-form').length && $('#send-invoice').length && $('#submit').length ){
			$('#submit').click(function(){
				Site.subscriptionSendInvoice();
			});
		}
		
	},
	
	subscriptionSendInvoice: function (){
		STATUS_PAID = 1;
		
		$('#send-invoice').attr('value', 0);

		if ( $('#orig-sub-paid').attr('value') != STATUS_PAID && $('#subscription_paid').val() == STATUS_PAID ){
			var sendInvoice = confirm("You have changed the status to PAID. Would you like a tax invoice to be emailed to the relevant party?");
			if (sendInvoice){
				$('#send-invoice').attr('value', 1);
			}
		}
	},
	
	orderSendInvoice: function (){
		STATUS_PAID = 3;
		
		$('#send-invoice').attr('value', 0);

		if ( $('#orig-status').attr('value') != STATUS_PAID && $('#status').val() == STATUS_PAID ){
			var sendInvoice = confirm("You have changed the status to PAID. Would you like a tax invoice to be emailed to the relevant party?");
			if (sendInvoice){
				$('#send-invoice').attr('value', 1);
			}
		}
		
	},
	
	pageIdRowAdd: function (){
		var i = $('.page-id-row').length;
		var new_row = $('#page-id-row-0').clone(true)
		
		new_row.appendTo('#page-id-container');
		
		new_row.find('input[type="text"]').attr('value', '');

		Site.pageIdRowRefresh();

	},
	
	pageIdRowRemove: function (row_i){
		$('#page-id-row-'+row_i).remove();
		Site.pageIdRowRefresh();
	},
	
	pageIdRowRefresh: function (){
		var rows = $('.page-id-row');
		rows.find('.delete-page-id-row').unbind('click');
		rows.find('.delete-page-id-row').show();
		
		rows.each( function ( i ){
			$(this).attr('id','page-id-row-'+i);
			$(this).find('.form-label label').html('iCMS Page ID #'+(i+1));
			
			if (i == 0){
				$(this).find('.delete-page-id-row').hide();
			}
			else {
				$(this).find('.delete-page-id-row').click( function (){
					Site.pageIdRowRemove(i);
				} );
			}
		} );
	},
	
	cycleFader:function() {
	
/* 		$('#user_interaction_right').cycle({
			fx: 'fade', 
			timeout: 5000,
			speed: 3000,
			pause:   1
			//next: '#next2',
			//prev: '#prev2'
		});
 */		
		$('#user_interaction').cycle({
			fx: 'fade', 
			timeout: 10000,
			speed: 3000,
			pause:   1
			//next: '#next2',
			//prev: '#prev2'
		});
		
/* 		$('#user_interaction_left').cycle({
			fx: 'fade', 
			timeout: 5400,
			speed: 3000,
			pause:   1,
			cleartypeNoBg: true
			//next: '#next2',
			//prev: '#prev2'
		});
 */		

		

		$('#quote-interaction').cycle({
			fx: 'fade', 
			timeout: 10000,
			speed: 3000,
			pause:   1,
			cleartypeNoBg: true
		});

	},
	
	featureWordParalax:function() {
		if($('#feature').length != 0) {
			$('#feature').parallax({
		      'elements': [
		        {
		          'selector': '#main',
		          'properties': {
		            'x': {
		              'background-position-x': {
		                'initial': 0,
		                'multiplier': 0.1,
		                'invert': true
		              }
		            }
		          }
		        },
		        {
		          'selector': 'div.outer',
		          'properties': {
		            'x': {
		              'background-position-x': {
		                'initial': 50,
		                'multiplier': 0.02,
		                'unit': '%'
		              }
		            },
					'y': {
						'background-position-y': {
							'initial': -15,
							'multiplier': 0,
							'unit': 'px'
						}
					}
		          }
		        },
		        {
		          'selector': 'div.inner',
		          'properties': {
		            'x': {
		              'background-position-x': {
		                'initial': 0,
		                'multiplier': 0.3
		              }
		            },
					'y': {
						'background-position-y': {
							'initial': 5,
							'multiplier': 0,
							'unit': 'px'
						}
					}
		          }
		        }
		      ]
		    });
		}
	},
	
	featureWords:function() {
				
			var scrollSpeed = 40;
			var step = 1;
			var current = 0;
			var imageWidth = 1594;
			var headerWidth = 1594;		
			var restartPosition = -(imageWidth - headerWidth);
		
			var scrollBg = function(){ 
				
				current -= step;
				if (current == restartPosition){
					current = 0;
				}
				
				$('#inspirational-words ul').css("background-position",current+"px 10px"); 
			}
		
			var init = setInterval(scrollBg, scrollSpeed);
	},

	featureSlide:function() {
		
		$('ul#user_interaction').carouFredSel({
				auto: 5000,
				scroll : {
					items : 1
				},
				items : {
					visible: 4
				},
				prev: "#prev1",
				next: "#next1"
		});
		
		$('ul#quote-interaction').carouFredSel({
				auto: 5000,
				scroll : {
					items : 1,					
					duration: 0,
					onBefore: function() {
					$("#quote-interaction").fadeOut('normal');
					},
					onAfter: function() {
					$("#quote-interaction").fadeIn('normal');
					}	
				},
				items : {
					visible: 3
				},
				prev: "#prev1",
				next: "#next1"
		});

	},
	
	search:function() {
		
		$('#search input').focus(function() {
			$(this).css({'background-position':'-280px -28px'});			
			$(this).prev('label').css({'left':'-9999px'});
		});
		
		$('#search input').blur(function() {
			$(this).css({'background-position':'-280px 0'});
			if ($(this).val() == '')
				$(this).prev('label').css({'left':'13px'});
		});
		
	},
	
	print:function() {
		
		$('#print-page').click(function(){
			window.print();
		});
		
	},
	
	externalLinks:function() {
	
		var extLinks = $('a.external');
			if ( extLinks.length ) {
				extLinks.each(function() { 
					$(this).attr('target', '_blank');
			});
		}
	
	},
	
	fancyBoxInit:function(){

		$("a[rel=gallery]").fancybox({
			'titleShow'			: 'False',
			'overlayColor'		: '#000000',
			'overlayOpacity'	: '.7'
		});
	},
	
	combobox:function() {
		$(".combobox" ).combobox();
	},
	
	datePicker: function (){
		$( ".datePicker" ).datepicker();
	},
	
	schoolEditForm: function (){

		$('#form_school_edit').validate();
	
		// School Status Select Toggle for Non Member
		$('#school_status').change( function(element) {
			
			if($(this).val() != '-2') { // If status is not 'deleted'
			
				if ($(this).val() == '-3'){	// Non Member School
					$('#school-map-location').hide();
					
					// Remove normal validation requirements for member schools
					$('#form_school_edit .required').each( function(){
						$(this).rules('add', { required: false });
					});
	
					// Add validation requirements for non-member school
					$('#form_school_edit .required-nonmember').each( function(){
						$(this).rules('add', { required: true });
					});
	
					// Hide all form rows
					$('#form_school_edit .form-row').each( function(){
						$(this).hide();
					});
					
					// Show only form rows required for non-member school
					$('#form_school_edit .form-row-nonmember').each( function(){				
						$(this).show();
					});
				}
				else {	// Member school
					$('#school-map-location').show();
					
					// Remove non-member school validation requirements
					$('#form_school_edit .required-nonmember').each( function(){
						$(this).rules('add', { required: false });
					});
	
					// Add normal validation requirements for member schools
					$('#form_school_edit .required').each( function(){
						$(this).rules('add', { required: true });
					});
	
					// Hide form rows for non-member schools
					$('#form_school_edit .form-row-nonmember').each( function(){				
						$(this).hide();
					});
				
					// Show all form rows
					$('#form_school_edit .form-row').each( function(){
						$(this).show();
					});
				}
			}
		});
	
		$('#school_status').change();
		
	},
	
	paymentTypes: function (){
		
		// Select default payment type if nothing is selected
		if ( $('#payment-type-options .payment-type-input:checked').length == 0 ){
			$('#payment-type-3d-secure').attr('checked', true);
		}
		
		// Toggle show/hide payment sections based on selected choice
		// and remove/add form validation requirements
		$('#payment-type-options .payment-type-input').change( function() {

			radio_inputs = $('#payment-type-options .payment-type-input');
			
			radio_inputs.each( function (){
				section_selector = '#payment-type-section-'+$(this).attr('value');
				
				if ( $(this).attr('checked') ){
					
					$(section_selector+' .required').each( function(){
						$(this).rules('add', { required: true });
					} );
					
					$(section_selector).show();
					
				}
				else {
					
					$(section_selector).hide();
					
					$(section_selector+' .required').each( function(){
						$(this).rules('add', { required: false});
					});
				}
				
			} );
			
		} );
		
		$('#payment-type-3d-secure').change();
		
	}
};

