var p;

$(document).ready(function(){

	// PROGRAMS NAV MENU
	p = $.parseJSON( $('#program_results .json').text() );
	updateProgsMenu(p, 'All Programs');
	$('#programs_subs li').hoverIntent(function(){
		var cat_id = $(this).data('category_id'),
			progs = [];

		if(cat_id=='search'){
			searchPrograms($('#programs_menu_search').val());
		} else {
			$.each(p, function(k,v){
				if(v.category_id == cat_id)
					progs.push( v );
			});
			updateProgsMenu(progs, $(this).find('a').text());
		}
	}, function(){} );

	function searchPrograms(query){
		var $loading = $('#program_results img.loading'),
			matched = [],
			reg = new RegExp("\\b" + query, 'i');

		if(query == '')
			return updateProgsMenu(p, 'Search');

		$loading.show();
		$.each(p, function(k, v){
			if(reg.test(v.title))
				matched.push( v );
		});
		updateProgsMenu(matched, 'Search - '+query);
	}
	$('#programs_menu_search').keyup(function(){
		var v = $(this).val();
		// if(v.length >= 2)
			searchPrograms(v);
	});

	function updateProgsMenu(p, title){
		var $heading = $('#program_results h5'),
			$content = $('#program_results .content'),
			$loading = $('#program_results img.loading'),
			$ul,
			alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

		$loading.show();
		$content.empty();

		// update the h5 title
		$heading.text(title);

		// if there's more than 8 programs we make list items
		if(p.length > 8){
			
			// split it into 3 even(ish) columns
			// make sure to account for the letters of the alphabet and the top ones
			var lists = array_chunk(p, Math.ceil(p.length/3)),	
			cur_letter;// don't set it to anything that way it will properly stick A into letter groups

			// each item in list is a ul
			$.each(lists, function(k,v){
				$ul = $('<ul></ul>').appendTo($content);

				// and then each item in v is a li
				$.each(v, function(k,v){
					// if the first letter of the title isn't the same as cur letter
					var letter = v.title.charAt(0).toUpperCase();
					if( letter !== cur_letter ){				
						// if it's the next letter just print that letter
						if( (alphabet.indexOf(letter) - alphabet.indexOf(cur_letter)) == 1){
							$ul.append('<li class="letter">' + letter + '</li>');
						// otherwise, do a grouping of all the characters inbetween here and there
						} else {
							var letter_group = [];
							for(i=alphabet.indexOf(cur_letter) + 1; i<=alphabet.indexOf(letter)-1; i++)
								letter_group.push( alphabet.charAt(i) );

							$ul.append('<li class="letter letter_group">' + letter_group.join(' ') + '</li>');
							$ul.append('<li class="letter">' + letter + '</li>');
						}
						cur_letter = letter;
					}

					var $li = $('<li></li>').appendTo($ul)
						.append(
							$('<a></a>').attr({
								href: 'programs/' + v.title_key,
								title: v.title
							})
							.text(v.title)
						);
				});
			});

			// and lets finish off the alphabet
			var letter_group = [];
			for(i=alphabet.indexOf(cur_letter) + 1; i<alphabet.length; i++)
				letter_group.push( alphabet.charAt(i) );
			$ul.append('<li class="letter letter_group">' + letter_group.join(' ') + '</li>');

		} else {
			// length <= 8 loop through and print logo links to each program
			$.each(p, function(k, v){
				var $div = $('<div></div>').appendTo($content)
					.addClass('logo_link')
					.append(
						$('<a></a>')
							.attr({
								href: 'programs/' + v.title_key,
								title: v.title
							})
							.addClass('logo')
							.css('background-color', '#' + v.logo_matte_color)
							.append(
								$('<img />').attr({
									src: 'uploads/images/program_logos/' + v.logo,
									alt: v.title + ' logo'
								})
							)								
					).append(
						$('<p></p>').append(
							$('<a></a>')
								.attr({
									href: 'programs/' + v.title_key,
									title: v.title
								})
								.text( v.title )
						)
					);
			});
		}

		$('#program_results img.loading').hide();
	}

	// LISTEN LIVE
	$('a.listen_live, a.wprrstream').click(function(){
		window.open('http://den-a.plr.liquidcompass.net/player/flash/audio_player.php?id=WPRRAM&uid=562', 'ListenLive', 'width=680,height=511, status=no,resizable=no,scrollbars=no');

		return false;
	});
	
	// TEL LINKS
	$('a:tel').addClass('tel');

	// EXTERNAL LINKS
	$('a:external').not('.social_icon').not('.site_icon').not('.no_icon').addClass('external').attr('target', '_blank');

	// SUBSCRIBE / FEED LINKS IN SUBNAV
	$('nav#sub a[href*="feed"], nav#sub a[title="Subscribe"]').prepend('<span class="social_icon icon_24 rss"></span>');

	// FORCE_DOWNLOAD LINKS
	// make an iframe with the url
	$('a.force_download').click(function(){
		$('<iframe>')
			.attr('src', $(this).attr('href'))
			.css('display', 'none')
			.appendTo('body');

		return false;
	});

	// SHARETHIS LINKS
	$('.sharethis a').not('.allow_click').click(function(){
		return false;
	});
	
	// STAFF VIDEO BUTTONS/MODALS
	$('.staff p.staff_video').button({
		icons: {
			primary: "ui-icon-video"
		}
	}).click(function(){
		var staff_name = $(this).parents('section.staff').find('h3').text();
		console.log(staff_name);

		$(this)
			.parents('section.staff')
			.find('div.video')
			.clone()
			.dialog({
				modal: true,
				minWidth: 480,
				dialogClass: 'staff_video_dialog',
				title: staff_name,
				buttons: {
					Ok: function(){
						$(this).dialog('close');
					}
				}
			});

		return false;
	});

	// SCHEDULE CALENDAR
	if($('#schedule').length && $.isFunction($.fn.fullCalendar)){
		$.scheduleHover.setPopup( $('#schedule_hover') );

		$('#schedule').fullCalendar({
			header: {
				left: 'prev,next today',
				center: 'title',
				right: 'month,agendaWeek,agendaDay'
			},
			editable: false,
			allDayDefault: false,
			allDaySlot: false,
			defaultView: 'agendaWeek',
			events: "ajax_schedule.php",		
			loading: function(bool) {
				if (bool) $('#schedule_loading').show();
				else $('#schedule_loading').hide();
			},
			eventClick: function(calEvent, jsEvent, view) {
				
				// console.log(calEvent, jsEvent, view);

				// return false;
			},
			eventMouseover: function(calEvent, jsEvent, view){
				$.scheduleHover.show(calEvent, this );
			},
			eventMouseout: function(calEvent){
				$.scheduleHover.hide();
			},
			viewDisplay: function(view) {
				var n = view.name,
					body_h = $('div.fc-view-'+n+' > div > div > div').height();

				$('div.fc-view-'+n+' > div > div, div.fc-view-'+n+' .fc-agenda-days').height(body_h + 20 +'px');
				$('div.fc-view-'+n+' .fc-agenda-days thead th').height(20);
			}
		});
	}


	// EPISODE DESCRIPTION TOGGLER
	$('#full_episodes p.desc_toggler a').click(function(){
		var $t = $(this),
			$desc = $t.parent().next('div.description');

		if($desc.is(':hidden')){
			$desc.slideDown();
			$t.text('hide description');
		} else {
			$desc.slideUp();
			$t.text('view description');
		}
		return false;
	});

});

function makeDialog(text, dialog_title, buttons, width, height, hideTitleBar){
	// make sure there isn't already a dialog open
	if($('#made_dialog').length)
		$('#made_dialog').dialog('close');

	if(!buttons){
		buttons = {
			Ok: function() {
				$(this).dialog('close');
			}
		}
	}

	$('<div id="made_dialog">'+text+'</div>').dialog({
		title: dialog_title,
		//dialogClass: hideTitleBar ? 'hide_title' : 'alert',
		bgiframe: true,
		modal: true,
		stack:true,
		autoOpen:true,
		width: width ? width : 460,
		minHeight: height ? height : 220,
		draggable: true,
		resizable: true,
		buttons: buttons,
		close: function(event, ui){
			$(this).remove();
		}
	});
}

// Creating custom :tel selector
$.expr[':'].tel = function(obj){
	return obj.href.match(/^tel\:/);
};
// Creating custom :external selector
$.expr[':'].external = function(obj){
	return !obj.href.match(/^mailto\:/)
		&& (obj.hostname != location.hostname);
}; 


function array_chunk (input, size, preserve_keys) {
    // http://kevin.vanzonneveld.net
    // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: Important note: Per the ECMAScript specification, objects may not always iterate in a predictable order
    // *     example 1: array_chunk(['Kevin', 'van', 'Zonneveld'], 2);
    // *     returns 1: [['Kevin', 'van'], ['Zonneveld']]
    // *     example 2: array_chunk(['Kevin', 'van', 'Zonneveld'], 2, true);
    // *     returns 2: [{0:'Kevin', 1:'van'}, {2: 'Zonneveld'}]
    // *     example 3: array_chunk({1:'Kevin', 2:'van', 3:'Zonneveld'}, 2);
    // *     returns 3: [['Kevin', 'van'], ['Zonneveld']]
    // *     example 4: array_chunk({1:'Kevin', 2:'van', 3:'Zonneveld'}, 2, true);
    // *     returns 4: [{1: 'Kevin', 2: 'van'}, {3: 'Zonneveld'}]
    
    var x, p = '', i = 0, c = -1, l = input.length || 0, n = [];
    
    if (size < 1) {
        return null;
    }

    if (Object.prototype.toString.call(input) === '[object Array]') {
        if (preserve_keys) {
            while (i < l) {
                (x = i % size) ? n[c][i] = input[i] : n[++c] = {}, n[c][i] = input[i];
                i++;
            }
        }
        else {
            while (i < l) {
                (x = i % size) ? n[c][x] = input[i] : n[++c] = [input[i]];
                i++;
            }
        }
    }
    else {
        if (preserve_keys) {
            for (p in input) {
                if (input.hasOwnProperty(p)) {
                    (x = i % size) ? n[c][p] = input[p] : n[++c] = {}, n[c][p] = input[p];
                    i++;
                }
            }
        }
        else {
            for (p in input) {
                if (input.hasOwnProperty(p)) {
                    (x = i % size) ? n[c][x] = input[p] : n[++c] = [input[p]];
                    i++;
                }
            }
        }
    }
    return n;
}

/**
* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne brian(at)cherne(dot)net
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev])}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev])};var handleHover=function(e){var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type=="mouseenter"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob)},cfg.timeout)}}};return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover)}})(jQuery);
