$(function(){
	/*
		GLOBALS
	*/
	TIMERS = {
		'search':null,
		'genre_works_interval':null,
		'genre_ajax_loader':null
	};
	
	current_search = null;
	
	current_genre_name = 'All Works';
	
	//keep track of whether colorbox is open
	colorbox_is_open = false;
	$(document).bind('cbox_open',function(){
		colorbox_is_open = true;
	});
	$(document).bind('cbox_closed',function(){
		colorbox_is_open = false;
	});
	
			
	/*  checking to see what's clicked */
	//$(window).click() not working in IE8...?
	$('body').click(function(ev){
		var $target = $(ev.target || ev.srcElement);//srcElement for IE
		if( ! $target.parents().filter('#music_player').length ){
			//one of the target's parents is not the music player, so hide the playlist
			if($('#jplayer_playlist').is(':visible')){
				$('#jplayer_playlist').hide();
			}
		}

		if( ! $target.parents().filter('#search_box').length ){
			//one of the target's parents is not the music player, so hide the playlist
			if($('#search_results_wrapper').is(':visible')){
				$('#search_results_wrapper').hide();
			}
		}

	});

	
	/*
		Positioning and Navigation
	*/
	var 
		current_page_index = 0; // also to be used with the navigation functions
		//pages on a 3 x 3 grid
		$page = $('.page_container').eq(0),
		page_width = $page[0].offsetWidth, /* width + padding*/
		page_height = $page[0].offsetHeight,
		page_margin_top = parseInt( $page.css('marginTop'),10 ),  /* height + padding */
		page_margin_bottom = parseInt( $page.css('marginBottom'),10 ),  /* height + padding */
		page_margin_horizontal = parseInt( $page.css('marginLeft'),10 ),
		total_page_height = page_height + page_margin_top - page_margin_bottom;
	
	function get_page_coords(page_index){
		var
			window_width = Math.max( $(window).width(), page_width ),
			window_height = Math.max( $(window).height(), total_page_height),
			page_index = (page_index !== undefined ? page_index : current_page_index),
			col = page_index % 3,
			row = Math.floor( page_index / 3 ),
			coords = {
				'x':0 - col * (page_width + page_margin_horizontal*2) + (window_width - page_width) / 2 - page_margin_horizontal,
				'y': (window_height - total_page_height) / 2 - page_margin_bottom - row * ( page_height + page_margin_top + page_margin_bottom )
			};
			
			try{
			    console.log('row:' +row+', col:'+col);
		    }catch(e){
		        
		    }
						
		return coords;
	}
		
	function center_everything(){
		//vars for the header
		var 
			window_width = Math.max( $(window).width(), page_width ),
			window_height = Math.max( $(window).height(), total_page_height),
			$header = $('#header'),
			coords = get_page_coords(),
			$pages_wrapper = $('#pages_wrapper');
			
		//header stuff
		$header.css({
			'top':(window_height - total_page_height) / 2
		});
		$pages_wrapper.css({
			'marginTop':coords.y
		});
		$header.css({
			'left':(window_width - $header.width()) / 2
		});
		$pages_wrapper.css({
			'marginLeft':coords.x
		});
	}

	center_everything();
	$(window).resize(center_everything);
	
	// showing body ( hid because header and page containers start out of position )
	$('body').css({'visibility':'visible'});

	
		
	var
		page_nav_array = [
			{
				'hash':'',
				'link_elem':'#home_link',
				'dest_elem':'#home_page'
			},		
			{
				'hash':'life',
				'link_elem':'#life_link',
				'dest_elem':'#life_page'
			},
			{
				'hash':'news',
				'link_elem':'#news_link',
				'dest_elem':'#news_page'
			},
			{
				'hash':'works',
				'link_elem':'#works_link',
				'dest_elem':'#works_page'
			},
			{
				'hash':'recordings',
				'link_elem':'#recordings_link',
				'dest_elem':'#recordings_page'
			},
			{
				'hash':'performances',
				'link_elem':'#performances_link',
				'dest_elem':'#performances_page'
			},
			{
				'hash':'photos',
				'link_elem':'#photos_link',
				'dest_elem':'#photos_page'
			},
			{
				'hash':'press',
				'link_elem':'#press_link',
				'dest_elem':'#press_page'
			},
			{
				'hash':'contact',
				'link_elem':'#contact_link',
				'dest_elem':'#contact_page'
			},
			{
				'hash':'vincent',
				'link_elem':'#vincent_link',
				'dest_elem':'#vincent_page'
			}
		];
		
		
	
	function go_to_page($dest_page,opts){
		var
			settings = (function(){
				var ret = { 'callback':function(){} };
				if( opts !== undefined){
					ret = $.extend(ret,opts);
				}
				return ret;
			})(),
			$page_containers = $('.page_container'),
			page_index = $page_containers.index($dest_page),
			coords = get_page_coords(page_index),
			$pages_wrapper = $('#pages_wrapper');
		
		//making sure it's not there already
		if( ! ( parseInt( $pages_wrapper.css('marginLeft'),10 ) === coords.x && parseInt( $pages_wrapper.css('top'),10 ) === coords.y  ) ){
			var 
				$current_tab = (function(){
					for(var i = 0, length = page_nav_array.length; i < length; i++){
						if( $dest_page.is( page_nav_array[i].dest_elem ) ){
							return $( page_nav_array[i].link_elem );
						}
					}
				})();
				
			//not local 
			current_page_index = page_index;

			//set the current page in navigation
			$('#nav_links li,.home_link').removeClass('current');
			$current_tab.addClass('current');
			
			//stop current scrolling if necessary
			if($pages_wrapper.is(':animated')){
				$pages_wrapper.stop();
			}
			
			//show all pages during scrolling
			$page_containers.css({'visibility':'visible'});
			//scroll to new page
			$pages_wrapper.animate({'marginLeft':coords.x,'marginTop':coords.y},1200,'easeOutCubic',function(){
				// hide the other pages so that word searching and tabbing doesn't move the wrapper_inner
				$page_containers.not(':eq('+page_index+')').css({'visibility':'hidden'});
				//this is where the callback takes place if called from a separate page
				settings.callback();
			});
		}else{
			//so we're on the same page, but the search bar has a callback it's interested in
			settings.callback();
		}
	}			

	//sets the hash	
	$('#nav_links li,#home_link').click(function(){
		var 
			$this = $(this),
			page_hash = (function(){
				for(var i = 0, length = page_nav_array.length; i < length; i++){
					if( $this.is( page_nav_array[i].link_elem ) ){
						return page_nav_array[i].hash;
					}
				}
				return false;
			})();
		
		if(page_hash !== false && document.location.hash.substr(1) != page_hash){
			document.location.hash = page_hash;
		}
	});
	
	//hash change gets detected
	$(window).bind('hashchange',function(){
		// hash gets set, then
		var 
			hash = document.location.hash.substr(1),
			$dest_page = (function(){
				for(var i = 0, length = page_nav_array.length; i < length; i++){
					if( hash == page_nav_array[i].hash ){
						return $( page_nav_array[i].dest_elem );
					}
				}
				return false;
			})();
		
		go_to_page($dest_page);
	});
	
	//if a hash has a length on page load
	(function(){
		var hash = document.location.hash.substr(1);
		if(hash.length){
			$(window).trigger('hashchange');
		}else{
			//hides remaining page containers, so no weird tabbing or anything
			$('.page_container').not(':eq('+current_page_index+')').css({'visibility':'hidden'});
		}
	})();
	
	
	/* setting options for life left menu */
	$life_right_panels = $('#life_page ul.right_panel li');
	$('#life_page .left_menu').left_menu({
		'link_callback':function(){
			//$links are defined in the left_menu jquery extension
			var index = $('#life_page .left_menu h3').index( this );
			$life_right_panels.removeClass('current').filter(':eq('+index+')').addClass('current');			
		}
	});
	
	/*
		SEARCH STUFF
	*/
	function perform_search(opts){
		var 
			defaults = {
				'timeout_ms':300,
				'view_all_results':false
			},
			settings = $.extend(defaults,opts),
			$results_wrapper = $('#search_results_wrapper'),
			$work_results_ul = $('#work_results'),
			$work_results_header = $('#work_results_header'),
			$recording_results_ul = $('#recording_results'),
			$recording_results_header = $('#recording_results_header'),
			$news_item_results_ul = $('#news_item_results'),
			$news_item_results_header = $('#news_item_results_header'),
			keywords = $('#id_search').val();

		if(TIMERS.search !== null){
			clearTimeout(TIMERS.search);
		}
		if(keywords.length < 2) {
			$results_wrapper.fadeOut();
			return false;
		}

		TIMERS.search = setTimeout(function(){
			if(current_search !== null){
				current_search.abort();
			}
			//perform search here current_search is a global
			current_search = $.ajax({
				url: '/search/ajax/',
				data:{
					'keywords':keywords,
					'view_all_results':settings.view_all_results
				},
				datatype:'json',
				type:'POST',
				success:function(r){
					if(settings.view_all_results){
						$.colorbox({
							'html':r.results.html,
							'opacity':.6,
							'width':600,
							'height':700
						});
						//bindings
						$('.all_search_results_work_title').click(function(){
							var work_id = $(this).siblings('input[type=hidden]').val();
							open_work_externally(work_id);
						});
						$('.all_search_results_recording_title').click(function(){
							var recording_id = $(this).siblings('input[type=hidden]').val();
							open_recording_externally(recording_id);
						});
					}else{
						var 
							result_count= {
								'works': r.results.works.length,
								'recordings': r.results.recordings.length
							},
							total_results = result_count.works + result_count.recordings,
							max_results = Math.min(5,total_results),
							category_maxes = (function(){
								var 
									r = [
										['works',0],
										['recordings',0]
									],
									i=0,
									item,
									ret = {};
								while( r[0][1] +r[1][1] < max_results){
									item = r[i % 2];
									if( result_count[item[0]] > item[1] ){
										item[1]++;
									}
									i++;
								}
								$.each(r,function(i,item){
									ret[ item[0] ] = item[1];
								});

								return ret;
							})(),
							has_results = false,
							extra_results = false;

						/* works */
						$work_results_ul.empty();
						if(r.results.works.length){
							has_results = true;
							$work_results_header.show();
							for( var i = 0; i < category_maxes.works;i++ ){
								$work_results_ul.append('<li>'+ r.results.works[i] +'</li>');
							}

							//bind the results
							$work_results_ul.find('li').click(function(){
								var $this = $(this),
								work_id = $this.find('input[type=hidden]').val();
								open_work_externally(work_id);
								$results_wrapper.hide();
							});
						}else{
							$work_results_header.hide();
						}

						/* recordings */
						$recording_results_ul.empty();
						if(r.results.recordings.length){
							has_results = true;
							$recording_results_header.show();
							for( var j = 0; j < category_maxes.recordings;j++ ){
								$recording_results_ul.append('<li>'+ r.results.recordings[j] +'</li>');
							}

							//bind the results
							$recording_results_ul.find('li').click(function(){
								var $this = $(this),
								recording_id = $this.find('input[type=hidden]').val();
								open_recording_externally(recording_id);
								$results_wrapper.hide();
							});
						}else{
							$recording_results_header.hide();
						}


						if(! has_results){ 
							$('#no_search_results').show();
						}else{ 
							$('#no_search_results').hide();
						}
						if(total_results > max_results){
							$('#all_search_results_link').show();
						}else{ 
							$('#all_search_results_link').hide();
						}
						$results_wrapper.show();
					}
					
				}
			});
		},settings.timeout_ms);

	}
	
	
	
	$('#id_search').focus(function(){
		var $this = $(this);
		if($this.val().toLowerCase() == 'search'){
			$this.val('');
		}else{
			$this.select();
		}
	}).keyup(function(){
		perform_search();
	});
	
	//make view all results work
	$('div#all_search_results_link span').click(function(){
		perform_search({
			timeout_ms:0,
			view_all_results:true
		});
		$('#search_results_wrapper').hide();
	});
	
	
	
	/*
		HOMEPAGE
	*/
	var paper = Raphael($('#homepage_photo_container')[0], 500, 800);
	var img = paper.image("/static/images/photos/homepage_photo.png", 10,5,472,640);
	img.rotate(-1.4);
	
	
	/* WORKS PAGE*/
	function works_genre_click(){
		var 
			$this = $(this),
			inner_text = $.trim( $this.text() ).toLowerCase(),
			genre_id = (function(){
				if(inner_text == 'all'){
					if( $this.is('h1,h2,h3,h4,h5,h6') ){
						return 0;
					}else if( $this.is('ul.subitems li') ){
						var $parent_genre = $this.parent().siblings('h1,h2,h3,h4,h5,h6');
						return $parent_genre.attr('id').substr(6);
					}
				}else{
					return $this.attr('id').substr(6);
				}
			})(),
			$works_list_container = $('#works_page .right_panel');
			
		TIMERS.genre_ajax_loader = setTimeout(function(){
			$works_list_container.html('<li><img src="/static/images/graphics/ajax-loader.gif" alt=""/></li>');
		},200);
		
		$.ajax({
			'data':{
				'genre_id':genre_id
			},
			'dataType':'json',
			'url':'/works/ajax/works_by_genre/',
			'success':function(r){
				if(TIMERS.genre_ajax_loader !== null){
					clearTimeout(TIMERS.genre_ajax_loader);
				}
				current_genre_name = r.current_genre_name;//current_genre_name is a global
				$works_list_container.html(r.works_html);
				bind_works();
			}
			
		});
	}
	
	/* setting options for works left menu */
	$('#works_page .left_menu').left_menu({
		'link_callback'   :works_genre_click,
		'sublink_callback':works_genre_click
	});
	
	function bind_works(){
		$('.work_list_title').colorbox({
			opacity:.6,
			current:'{current} of {total} in '+current_genre_name,
			width:600,
			height:600,
			transition:'none'
		});
	}
	bind_works();
	
	function open_work_externally(work_id){
		if(! $('#work_list_link_' + work_id).length ){
			//click on 'all works'
			$('#works_page .left_menu li:eq(0)>h3:eq(0)').trigger('click');
		}
		
		//first close the colorbox
		var open_after_cbox_closed = function(){
			$(document).unbind('cbox_closed',open_after_cbox_closed);//need to unbind as well
			go_to_page($('#works_page'),{
				'callback':function(){
					//just setting an interval instead of reworking the left menu stuff
					var 
						kill_iteration = 300,//30 seconds
						current_iteration = 0,
						interval_ms = 100;

					TIMERS.genre_works_interval = setInterval(function(){
						if( $('#work_list_link_' + work_id).trigger('click').size() || current_iteration == kill_iteration ){
							clearInterval(TIMERS.genre_works_interval);
						}
						current_iteration++;
					},interval_ms);
					document.location.hash = 'works'
				}
			});
		};
		$(document).bind('cbox_closed',open_after_cbox_closed);
		
		//global colorbox_is_open
		if( colorbox_is_open ){
			$.colorbox.close();			
		}else{
			$(document).trigger('cbox_closed');			
		}
	}
	

	
	/* 
		recordings_page
	*/
	$('.recording_table_title').colorbox({
		opacity:.6,
		current:'Recording {current} of {total}',
		width:650,
		height:400,
		transition:'none',
		onComplete:function(){
			//open work
			$('.recording_work_title').click(function(){
				var work_id = $(this).siblings('input[type=hidden]').val();
				open_work_externally(work_id);
			});
		}
	});
	
	
	function open_recording_externally(recording_id){		
		//first close the colorbox
		var open_after_cbox_closed = function(){
			$(document).unbind('cbox_closed',open_after_cbox_closed);//need to unbind as well
			go_to_page($('#recordings_page'),{
				'callback':function(){
					$('#recordings_table_title_' + recording_id).trigger('click');
					//this comes last intentionally
					document.location.hash = 'recordings'
				}
			});
		};
		$(document).bind('cbox_closed',open_after_cbox_closed);
		
		//global colorbox_is_open
		if( colorbox_is_open ){
			$.colorbox.close();			
		}else{
			$(document).trigger('cbox_closed');			
		}
	}
	
	
	/*
		performances page
	*/
	$('#performances_page .left_menu').left_menu();
	
	function search_performances(opts){
		//searches upcoming with no keywords by default
		var 
			settings = (function(){
				var 
					d = new Date(),
					defaults = {
						'keywords':'',
						'date_gte':d.getFullYear()+'-'+ (d.getMonth() + 1 ) * 1 + '-' + d.getDate(),
						'dates_ascending':true
					};
				
				return (opts !== undefined ? $.extend(defaults,opts) : defaults );
			})(),
			$perf_table_body = $('#performances_page table#performances_table tbody').empty();
		
		$perf_table_body.html('<tr><td style="border-bottom:0;"><img src="/static/images/graphics/ajax-loader.gif" alt=""/></td></tr>');
		
		$.get('/performances/ajax/search/',settings,function(r){
			$perf_table_body.empty();
			if(r.performance_html_list.length){
				$.each(r.performance_html_list,function(i,item){
					$perf_table_body.append(item);
				});
			}else{
				$perf_table_body.html('<tr><td>No performances found.</td></tr>');
			}
			bind_performances();
		},'json');
	}
	
	$('#upcoming_performances_link').click(function(){
		//searches upcoming by default
		search_performances();
	});
	
	$('#all_performances_link').click(function(){
		search_performances({
			'date_gte':'1980-12-12',
			'dates_ascending':false
		});
	});
	
	search_performances();
	
	function bind_performances(){
		$('.performance_work_external_link').click(function(){
			var work_id = $(this).siblings('input[type=hidden].performance_work_hidden_id').val();
			open_work_externally(work_id);
		});
	}
	
	/*
		Press Quotes
	*/
	$('.press_work_title').click(function(){
		var work_id = $(this).siblings('input[type=hidden]').eq(0).val();
		open_work_externally(work_id);
	});
	
	
	/*
		Press Photos
	*/
	$('#press_page .left_menu').left_menu({
		link_callback:function(){
			var 
				$this = $(this).parent(),
				index = $('#press_page .left_menu li').index($this);
			
			$('#press_page .right_panel li').hide().filter(':eq('+index+')').show();
		}
	});
	
	/*
		News Page
	*/	
	$('.news_headline_ajax').colorbox({
		width:650,
		height:700,
		opacity:.6,
		current:'{current} of {total} in News'
	});
	
	function open_news_item_externally(news_id){
		//first close the colorbox
		var open_after_cbox_closed = function(){
			$(document).unbind('cbox_closed',open_after_cbox_closed);//need to unbind as well
			go_to_page($('#news_page'),{
				'callback':function(){
					$('#news_headline_' + news_id).trigger('click');
					//this comes last intentionally
					document.location.hash = 'news'
				}
			});
		};
		$(document).bind('cbox_closed',open_after_cbox_closed);
		
		//global colorbox_is_open
		if( colorbox_is_open ){
			$.colorbox.close();			
		}else{
			$(document).trigger('cbox_closed');
		}
	}
	
	
	/* 
		HOMEPAGE
	*/
	$('.homepage_news_link').click(function(){
		var news_id = $(this).siblings('input[type=hidden]').val();
		open_news_item_externally(news_id);
	});
	
	/*
		PHOTOS PAGE
	*/
	$('#photos_page .left_menu').left_menu({
		'link_callback':function(){
			var
				$this = $(this),
				li_index = $('#photos_page ul.menu_items li').index( $this.parent() );
		
			$('#photos_page .right_panel > li').hide().filter(':eq('+li_index+')').show();
		}
	});
	
	$('.photo_gallery_thumb_link').colorbox({
		width:1000,
		height:700,
		opacity:.6,	
	});
	
	/*
		CONTACT PAGE
	*/
	$('#contact_page .left_menu').left_menu({
		'link_callback':function(){
			var
				$this = $(this),
				li_index = $('#contact_page ul.menu_items li').index( $this.parent() );
			
			$('#contact_page .right_panel > li').hide().filter(':eq('+li_index+')').show();
		}
	});
	
	function hide_hp(){
		$('.contact_form').find('input[name=phone]').parent().addClass('hp_container');		
	}
	hide_hp();
	$('.contact_form input[type=submit]').live('click',function(){
		var 
			$form = $(this).parents('.contact_form'),
			submit_url = $.trim( $form.find('.contact_form_submit_url').text() ),
			submit_data = (function(){
				var ret = {};
				$form.find('input[type=text],textarea').each(function(){
					var $input = $(this);
					ret[$input.attr('name')] = $input.val();
				});
				return ret;
			})();
								
		$.post(submit_url,submit_data,function(r){
			$form.replaceWith(r);
			hide_hp();
		});
		
		$form.children().hide().end().append('<img src="/static/images/graphics/ajax-loader.gif"/>');
		
		return false;
	});
	
	
	/*
	    VINCENT PAGE
	*/
	$('#vincent_page .left_menu').left_menu({
		'link_callback':function(){
			var
				$this = $(this),
				li_index = $('#vincent_page ul.menu_items li').index( $this.parent() );
			
			$('#vincent_page .right_panel > li').hide().filter(':eq('+li_index+')').show();
		}
	});
	
	$('.vincent_review_dropdown_link').click(function(){
	    $(this).siblings('.vincent_review_dropdown').toggle();
	    
	    return false;
	});
	
	
});
