var HY   =   {};


HY.teamSortable = function( table )
{
	
	var obj				=	this;							//	grab "this" at top level
	this.table			=	table;							//	jquery object of the table
	this.members		=	this.table.find('tbody tr');	//	jquery object of member rows
	this.upButtons		=	this.table.find('a.move_up');	//	all of the move up bottons
	this.downButtons	=	this.table.find('a.move_down');	//	all of the move down buttons
	this.memberOrder	=	{};								//	json object to hold the order of members
	

	//	when a down button is clicked, move that person up
	this.upButtons.click( function()
	{
		var movedItem	=	$(this).parent().parent('tr');
		movedItem.after( movedItem.prev() );
		obj.saveOrder();
		return false;
	});
	

	//	when a down button is clicked, move that person down
	this.downButtons.click( function()
	{
		var movedItem	=	$(this).parent().parent('tr');
		movedItem.before( movedItem.next() );
		obj.saveOrder();
		return false;
	});
	
	
	//	save the current positions of members
	this.saveOrder	=	function()
	{		
	
		//	loop through the members and find their positions in the table
		//	then load up the json object with that data
		this.table.find('tbody tr').each(function(i)
		{
			var memberId	=	$(this).attr('id');
			obj.memberOrder[i] = memberId;
		});

		//	make the ajax call, then do something on success
		$('#team_sortable_status span').css('display', 'inline');
		
		$('#team_sortable_status span').html('Saving ...');
		
		$.ajax(
		{
			type: "POST",
			url: "/admin/team/category/organize/",
			data: obj.memberOrder,
			success: function () {
				$('#team_sortable_status span').html('Changes saved!');
				
			}
		});
	};
	
};



HY.Rotator   =   function( obj )
{
	// inserts nav list dots
	this.addNav	=	function()
	{
		var navList	=	'<ul class="scrollNav"><li class="current">1</li></ul>';
		this.products.prepend(navList);
		
		for (var i=1; i < this.pane_count; i++) 
		{
			var navItem	=	'<li>'+i+'</li>';
			$('.scrollNav').append(navItem);
		}
	};	
	
    var cc                  =   this;           					//  cached 'this'
    this.products           =   $('#featured_wrap');           			
    this.pane_wrap          =   $('#featured_pane');
    this.panes              =   $('.featured');                     //  individual product panes
	this.pane_count			=	this.panes.length;					//	# of panes
	this.addNav();													//	run addNav to make the nav UL
	this.nav				=	this.products.find(".scrollNav");	//	navigation dots UL
    this.leftBtn            =   $('#left a');				    	//	left button
    this.rightBtn           =   $('#right a');				        //	right button
    this.current_pane		=	1;									//	pointer of which pane is currently shown
	
	//	sets the wrap to the length it needs to be to fit all panes
	this.pane_wrap.css( 'width', (this.pane_count * 520) );		
	
	//	when the right button is clicked
	this.rightBtn.click(function()
	{
		if ( cc.current_pane < cc.pane_count ) 
		{
	        cc.pane_wrap.animate(
	        { 
	        	marginLeft: "-=500px"
	        }, 
			400 );
			
			cc.current_pane++;
			cc.nav.find('.current').removeClass('current');
			cc.nav.find('li:eq('+(cc.current_pane - 1)+')').addClass('current');
		}

		$(this).blur();
        return false;
	});
	
	//	when the left button is clicked
 	this.leftBtn.click(function()
	{
		if ( cc.current_pane > 1 ) 
		{
	        cc.pane_wrap.animate(
	        { 
	        	marginLeft: "+=500px"
	        }, 
			400 );
			
			cc.current_pane--;
			cc.nav.find('.current').removeClass('current');
			cc.nav.find('li:eq('+(cc.current_pane - 1)+')').addClass('current');
		}

        $(this).blur();
        return false;
	});

};	//	end HY.Rotator



/////////////////
// set pagination

HY.setPagination = function (items_per_page, total_item_count, pagination_target, base_url)
{
    var items_per_page          = items_per_page;
    var total_item_count        = total_item_count;
    var pagination_target       = pagination_target;
	var base_url                = base_url;

    // Create pagination element
    pagination_target.pagination(total_item_count, {
    	num_edge_entries: 2,
    	num_display_entries: 8,
    	link_to: base_url + '__id__',
    	items_per_page: items_per_page,
        callback: pageselectCallback
    });
    
    
    ///////////////////////
    // page change callback
    
    function pageselectCallback( page_id, paginationBlock ) {
		// set count element, pagination target
	    paginationTarget    = paginationBlock.parent().find('.pagination_section');
	    totalCount          = paginationBlock.parent().find('.count span');

	    // append loader animation
	    $('body').append('<div id="TB_load" style="width: 66px; height: 66px;"><img src="/images/layout/ajax_pagination.gif" /></div>');//add loader to the page
	    $('#TB_load').show();

		//Fade the element, to let the user know something is going on
		paginationTarget.fadeTo("slow", 0.25, function () {	
		$.ajax({
			type: "GET",
			url: base_url + parseInt(page_id + 1),
			error: function ( XMLHttpRequest, textStatus, errorThrown )
		                {
			  // typically only one of textStatus or errorThrown will have info
			  alert(textStatus + ': ' + errorThrown); //this; // the options for this ajax request
			},
			complete: function ( XMLHttpRequest, textStatus ) {
				paginationTarget.html( XMLHttpRequest.responseText ).fadeTo("slow", 1.0);
	            $('#TB_load').remove();
	            // set last count item for total count display
	            if ( (page_id * items_per_page) + items_per_page < total_item_count )
	                { new_total = (page_id * items_per_page) + items_per_page; }
	            else
	                { new_total = total_item_count; }
           
	            // update total count display
	            totalCount.text( ((page_id * items_per_page) + 1) + ' - ' + new_total);
				}
			});
		});
	
		return false;
    }
};




HY.formEraserHelper	=	function(fieldObj)
{
	var obj				=	this;
	this.fieldObj		=	fieldObj;
	this.initialValue	=	this.fieldObj.val();
	
	this.fieldObj.focus(function()
	{
		if ( $(this).val() == obj.initialValue )
		{
			$(this).val('');
		}
	});
	
	this.fieldObj.blur(function()
	{
		if ( $(this).val() === '')
		{
			$(this).val(obj.initialValue);
		}
	});
};



$('document').ready(function()
{	

    //  admin section hide/show toggles for checkboxes
	$('#newsletters_forms_create input:checkbox').each( function()
	{
		if($(this).attr('checked') == false)
		{
			$(this).parent().parent().next().hide();			
		}
		
		$(this).click(function()
		{
			if($(this).attr('checked') == false)
			{
				$(this).parent().parent().next().hide();			
			}
			else
			{
				$(this).parent().parent().next().show();			
				
			}
		});
		
	});


	//	sortable team memebers in admin section
	$('.sortable_members').each( function()
	{
		HY.teamSortableTable = new HY.teamSortable($(this));
	});
	
	
	
	Date.firstDayOfWeek = 7;
	Date.format = 'mm/dd/yyyy';
	
	
	$('.datepicker').each( function()
	{
		HY.initialDate=new Date();
		HY.initialDate.setFullYear($('#published_on_year').val(), ($('#published_on_month').val()-1), $('#published_on_day').val());

		
		// date picker stuff
		$('.datepicker')
			.datePicker(
				// associate the link with a date picker
				{
					createButton:true,
					startDate: '01/01/2005'
				}
			)
			.dpSetSelected( HY.initialDate.asString() )
			.bind(
					// when the link is clicked display the date picker
					'click',
					function()
					{
						updateSelects($(this).dpGetSelected()[0]);
						$(this).dpDisplay();
						return false;
					}
				).bind(
					// when a date is selected update the SELECTs
					'dateSelected',
					function(e, selectedDate, $td, state)
					{
						updateSelects(selectedDate);
					}
				).bind(
					'dpClosed',
					function(e, selected)
					{
						updateSelects(selected[0]);
					}
			);
	});
	
	
	var updateSelects = function (selectedDate)
	{
		selectedDate = new Date(selectedDate);
		var d = selectedDate.getDate();
		var m = selectedDate.getMonth();
		var y = selectedDate.getFullYear();
		($('#published_on_day')[0]).selectedIndex = d - 1;
		($('#published_on_month')[0]).selectedIndex = m;
		($('#published_on_year')[0]).selectedIndex = y - 2004;
	};
	// listen for when the selects are changed and update the picker
	$('#published_on_day, #published_on_month, #published_on_year')
		.bind(
			'change',
			function()
			{
				var d = new Date(
							$('#published_on_year').val(),
							$('#published_on_month').val()-1,
							$('#published_on_day').val()
						);
				$('.datepicker').dpSetSelected(d.asString());
			}
		);

	// and update the datePicker to reflect it...
	$('#published_on_day').trigger('change');
	
	
	
	
	
	
	
	if( $('.clone_form').length >= 1 )
	{
		$('.clone_form').cloner( 
		{
			cloneFieldsetClass	:	'cloner',
			existingItemClass	:	'collateral_block_exists',
			removeClass			:	'remove',
			existsRemoveClass	:	'exists_remove',
			addLink				:	'add',
			deleteStateText		:	'Click "Save Changes" to delete or',
			deleteStateLink		:	'Keep Me'
		});
	}

	
	
    $('#featured_pane').each( function(i)
    {
        HY[$(this).attr('id')+'_'+i]    =   new HY.Rotator( $(this)[i] );
    });	

	//	tabbing system on front page
	$('.tabs_class').each(function()
	{
		var this_tab = $(this);
		
		$(this).click( function()
		{
			var tab_id	 = this_tab.attr('id');
			var content_id = tab_id+"_content";
			var content 	= $('#'+content_id);
			
			if( content.css('display') != 'block')
			{
				$('.tab_content:not(#'+content_id+')').fadeOut();
				content.fadeIn();
				$('#tabs .current').removeClass('current');
				this_tab.addClass('current');
			}
			
		return false;
		});
	});
	
	$('#mail').each( function()
		{
			var fieldName	=	$(this).attr('name');
			HY[fieldName]	=	new HY.formEraserHelper($(this));
	});

	$('#property_tabs').each( function()
	{
		var centered = 'no';
		$('#property_tabs > ul').tabs();
		
		$('.ui-tabs-nav').bind('tabsshow', function(event, ui) {
			if( $('.ui-tabs-selected > a').attr('id') == "tab_map" && centered == 'no') 
			{ 
				center_map();
				centered = 'yes';
			}
		});
	});

});
