/*
 * Adminica UI
 *
 * Copyright (c) 2010 Tricycle Interactive
 *
 * http://www.tricycle.ie
 *
 * This file configures all the different jQuery scripts used in the Adminica Admin template. Links to the scripts can be found at the beginning of each function
 *
 */
 
 
 $(function() {

//jQuery UI elements (more info can be found at http://jqueryui.com/demos/)
	
	// Sidenav Accordion Config
		$( "ul#accordion" ).accordion({
			collapsible: true,
			active:false,
			header: 'li a.top_level',
			autoHeight:false,
			icons:false
		});

	// Top Nav Dropdown Accordion Config				
		$( "ul.dropdown" ).accordion({
			collapsible: true,
			active:false,
			header: 'li a.has_slide', // this is the element that will be clicked to activate the accordion 
			autoHeight:false,
			event: 'mousedown',
			icons:false
		});
 	
 	// Content Box Toggle Config 
		$("a.toggle").click(function(){
			$(this).toggleClass("toggle_closed").next().slideToggle("slow");
			return false; //Prevent the browser jump to the link anchor
		});
 	
 	// Content Box Tabs Config
			$( ".tabs" ).tabs({ 
				fx: {opacity: 'toggle', duration: 'slow'} 
			});

			$( ".side_tabs" ).tabs({ 
				fx: {opacity: 'toggle', duration: 'slow', height:'auto'} 
			});
		

	// Content Box Accordion Config		
		$( ".content_accordion" ).accordion({
			collapsible: true,
			active:false,
			header: 'h3.bar', // this is the element that will be clicked to activate the accordion 
			autoHeight:false,
			event: 'mousedown',
			icons:false,
			animated: true
		});
		
	// Sortable Content Boxes Config				
		$( ".main_container" ).sortable({
			handle:'.grabber',  // the element which is used to 'grab' the item
			items:'div.box', // the item to be sorted when grabbed!
			opacity:0.8,
			revert:true,
			tolerance:'pointer',
			helper:'original',
			forceHelperSize:true,
			placeholder: 'dashed_placeholder',		
			forcePlaceholderSize:true
		});

	// Sortable Accordion Items Config			
		$( ".content_accordion" ).sortable({
			handle:'a.handle',
			axis: 'y', // the items can only be sorted along the y axis
			revert:true,
			tolerance:'pointer',
			forcePlaceholderSize:true
		});
		
	// Input Datepicker Config
		$( ".datepicker" ).datepicker({ dateFormat: 'd M yy' });; // the time format which will be input to the datepicker field upon selection. more info on formatting here: http://docs.jquery.com/UI/Datepicker/formatDate
	
	// input Slider	Config
		$( ".slider" ).slider(); // creates a simple slider with default settings
	
		
	// input Range Slider Config	
		$( ".slider_range" ).slider({
			range: true, // creates a range slider
			min: 0,
			max: 500,
			values: [ 75, 300 ],
			slide: function( event, ui ) {
				$( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
			}
		});
		
		$( "#amount" ).val( "$" + $( "#slider_range" ).slider( "values", 0 ) +
			" - $" + $( "#slider_range" ).slider( "values", 1 ) );
		
	// Dialog Config
		$( "#dialog" ).dialog({
			autoOpen: false, 
			show: "fade",
			hide: "fade",
			modal: true 
		});
		
		$( "#opener" ).click(function() {
			$( "#dialog" ).dialog( "open" ); // the #dialog element activates the modal box specified above
			return false;
		});
	
	//Progress Bar Config
		$( "#progressbar" ).progressbar({
			value: 25
		});
		
	// Dismiss alert box
		$(".alert").click(function(){
			$(this).fadeOut('slow');
		});
	
	// target nav items with a dropdown for styling.
	$('ul.dropdown').parent().addClass('has_dropdown');
				
	// wizard
	
	$('.wizard_steps ul li a').click(function(){
		$('.wizard_steps ul li').removeClass('current');
		$(this).parent('li').addClass('current');
		
		var step = $(this).attr('href');
		var step_num = $(this).attr('href').replace('#step_','');
		
		var prog_val = (step_num*25);
		
		$( "#progressbar").progressbar({ value: prog_val });
		
		$('.wizard_content').children().hide();
		$('.wizard_content').children(step).fadeIn();
		
		return false;
	});
	
	$('button.next_step').click(function(){
		
		var step = $(this).attr('id');
		var hash_step = ('#'+step);
		
		
		var step_num = $(this).attr('id').replace('step_','');
		var prog_val = (step_num*25);
		
		$( "#progressbar").progressbar({ value: prog_val });
		
		$('.wizard_steps ul li').removeClass('current');
		$('a[href='+ hash_step +']').parent().addClass('current');
		
		$('.wizard_content').children().hide();
		$('.wizard_content').children(hash_step).fadeIn();
		
		return false;
	});
	
		
// Other Scripts

	// Uniform Config (more info can found at http://pixelmatrixdesign.com/uniform/)
        $( "select, input:checkbox, input:radio, input:file").uniform();
	
    // Tipsy Top Config (more info found at http://onehackoranother.com/projects/jquery/tipsy/)
		$('[title]').tipsy({
			fade: true,     // fade tooltips in/out?
			fallback: '',    // fallback text to use when no tooltip text
			gravity: 's',    // gravity
			opacity: 1,    // opacity of tooltip
			title: 'title',  // attribute/callback containing tooltip text
			trigger: 'hover' // how tooltip is triggered - hover | focus | manual    	
		});  
		
	// Tipsy Side Config
		$('input[title]').tipsy({
			trigger: 'focus',  
			offset:'5',
			gravity: 'w'
		});
	
	// focus on first field in form
	//$("input[type='text']:first", document.forms[0]).focus();
	
		
	// iOS Device Touch Config (more info can be found at http://old.nabble.com/jQuery-UI-Support-on-the-iPhone-td22011162s27240.html)
	
		$('.main_container').sortable();
		$('.grabber').addTouch();
		$('ul.content_accordion').sortable();
		$('a.handle').addTouch();
		$('.ui-slider-handle').addTouch();
		
		if($('.table').length > 0){
	// DataTables Config (more info can be found at http://www.datatables.net/)
		var oTable = $('.table').dataTable( {
					"bJQueryUI": true,
					"sScrollX": "",
					"bSortClasses": false,
					"aaSorting": [],
					"bAutoWidth": true,
					"bInfo": true,
					"sScrollY": "100%",	
					"sScrollX": "100%",
					"bScrollCollapse": true,
					"sPaginationType": "full_numbers",
					"bPaginate": false,
					"bRetrieve": true
					} );
					
		$(window).bind('resize', function () {
				oTable.fnAdjustColumnSizing();
			} );


	// DataTables Config - this reloads dataTables when it is placed in a hidden tab			
		$(".tabs").tabs( {
            "select": function(event, ui) {
                $('.tabs div.dataTables_scroll').css({
                    "visibility":"hidden" 
                });
            },
            "show": function(event, ui) {
                var oTable = $('div.dataTables_scrollBody > table', ui.panel).dataTable();
                if ( oTable.length > 0 ) {
                    oTable.fnAdjustColumnSizing();
                    $(".tabs div.dataTables_scroll").css({
                        "display":"none",
                        "visibility":"visible" 
                    }).fadeIn("slow");
                }
            }
        } );

	// DataTables Config - this reloads dataTables when it is placed in a closed accordion			
		$( ".content_accordion" ).accordion( {
			"change": function(event, ui) {
				var oTable = $('div.dataTables_scrollBody > table', ui.panel).dataTable();
                if ( oTable.length > 0 ) {
                    oTable.fnAdjustColumnSizing();
                    $(".content_accordion div.dataTables_scroll").css({
                        "display":"none",
                        "visibility":"visible" 
                    }).show();
                }
				if ( oTable.length > 0 ) {
					oTable.fnAdjustColumnSizing();
				}
			}
		} );
		
	// static tables alternating rows
		$('table.static tr:even').addClass("even")
		
		}
	
	// FileTree Config (more info can be found at http://abeautifulsite.net/blog/2008/03/jquery-file-tree/)
		$('#file_tree').fileTree({ 
					root: '/var/www/vhosts/tricycle.ie/httpdocs/adminica/file_tree/', 
					script: '../../../js/jqueryFileTree/jqueryFileTree.php', 
					loadMessage:'Loading...'  }, function(file) {
					alert(file);
					});
	
	//FancyBox Config (more info can be found at http://www.fancybox.net/)
		$(".gallery ul li a").fancybox({
        'overlayColor':'#000' 
			
		});
		$("a img.fancy").fancybox();
	
	//This configures the iPhone style Contacts display)	  
 		$('#slider_list').sliderNav({height:'500'});

		

	//Slide to top link
		$().UItoTop({ easingType: 'easeOutQuart' });
		

	//Fullcalendar		
		
	    $('#calendar').fullCalendar({
	    		firstDay:'1',
	    		weekMode:'liquid',
	    		aspectRatio: '1.5',
				theme:true,
				selectable:true,
				editable:true,
				draggable:true,
				droppable:true,
				timeFormat:'H:mm',
		    	axisFormat:'H:mm',
		    	columnFormat:{
				    month: 'ddd',    // Mon
				    week: 'ddd dS', // Mon 9/7
				    day: 'dddd dS MMMM'  // Monday 9/7
				},
				titleFormat:{
				    month: 'MMMM yyyy',                             // September 2009
				    week: "MMM d[ yyyy]{ 'to'[ MMM] d, yyyy}", // Sep 7 - 13 2009
				    day: 'ddd, MMMM d, yyyy'                  // Tuesday, Sep 8, 2009
				},
		    	allDayText:'All Day',
				header:{
				    left:   'prev title next, today',
				    center: '',
				    right:  'agendaWeek,agendaDay,month'
					},
				
				eventSources: [

				        // your event source
				        {
				            events: [ // put the array in the `events` property
				                {
				                    title  : 'Company AGM',
				                    start  : '2011-04-03',
								    className:'calendar_green'
				                },
				                {
				                    title  : 'Business Trip',
				                    start  : '2011-04-15',
				                    end    : '2011-04-20',
								    className:'calendar_blue'
				                },
				                {
				                    title  : 'Day off',
				                    start  : '2011-04-08 12:30:00',
								    className:'calendar_red'
				                }
				            ]
				        },
				        {
						    url: 'https://www.google.com/calendar/feeds/nueoipsjhgm857gpojq5563cfo@group.calendar.google.com/public/basic',
						    className:'calendar_magenta'
						},
						{
							url: 'http://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/basic',
							className: 'calendar_navy'
						}
				
				
				    ],
				
				drop: function(date, allDay) { // this function is called when something is dropped
			
				// retrieve the dropped element's stored Event Object
				var originalEventObject = $(this).data('eventObject');
				
				// we need to copy it, so that multiple events don't have a reference to the same object
				var copiedEventObject = $.extend({}, originalEventObject);
				
				// assign it the date that was reported
				copiedEventObject.start = date;
				copiedEventObject.allDay = allDay;
				
				// render the event on the calendar
				// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
				$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
				
				// is the "remove after drop" checkbox checked?
				if ($('#drop-remove').is(':checked')) {
					// if so, remove the element from the "Draggable Events" list
					$(this).remove();
				}
				
			}
		        
		    });
		
		$('ul#calendar_drag_list li a').each(function() {
		
			// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
			// it doesn't need to have a start or end
			var eventObject = {
				title: $.trim($(this).text()), // use the element's text as the event title
				className: 'calendar_black'
			};
			
			// store the Event Object in the DOM element so we can get to it later
			$(this).data('eventObject', eventObject);
			
			// make the event draggable using jQuery UI
			$(this).draggable({
				zIndex: 999,
				revert: true,      // will cause the event to go back to its
				revertDuration: 5  //  original position after the drag
			});
			
		});
		
	    
	

});
