// Public module (aka global) javascript file.
var $j = jQuery.noConflict();
var $ = jQuery.noConflict();
var loginDoneTxt = '';
var loginDoneExe = '';
var memberData = '';

$j(document).ready(function() {	
	$j('div#subnav_2').show();

	$j('div#subnav_2 ul li.selected').children('ul').fadeIn();

	$j('div#subnav_2 ul li.reveal').click(
		function(e){
			if($j(this).hasClass('selected')){
				$j(this).removeClass('selected');
				$j(this).children('ul').hide();
			} else {
				$j(this).siblings().removeClass('selected');
				$j(this).addClass('selected');
				$j('div#subnav_2 ul li ul').hide();
				$j(this).children('ul').show();
			}
		}
	);	

	trav_loginform = '<br/><br/><br/><br/><br/><br/><br/><br/><h2>Log into your WIL Loyal Listener Account</h2><p>Please enter your email and password. <br /></p><form onsubmit="loginSubmit(); return false;" method="post" name="travloginform" id="travloginform"><input type="text" name="loginEmail" size="15" onfocus="if (this.value == \'Email Address\') {this.value = \'\';}" id="loginEmail" value="Email Address" /> <input size="15" type="password" name="loginPass" id="loginPass" /> <input type="submit" value=" Log in " /></form><ul class="signup"><li>Need a <strong>WIL Loyal Listener</strong> account? <a href="/public/member/signin#signup">Sign up <em>right here!</em></a></li></ul>';
	
	$j('a[rel*=facebox]').facebox();
  			
 	$j('a[rel*=login_link]').click(function(e){
		e.preventDefault();
		loginDoneExe = 'top_login_done()';
		loginDoneTxt = '';
		login();
	});
	
	// Add click events to all rel="popup" links
	$j('a[rel="popup"]').click(function(e){
		e.preventDefault();
        var params = new Array();
        if ($(this).attr("target")) { params.windowName = $(this).attr("target"); }
        
        var windowObject = popup(this.href, params);  
	});	
	
	activatebar();
	
	// Add calendar rollover
	jQuery('div#calendar_widget').hover(function(){ jQuery('#calendar_fill').slideDown(); }, function(){ jQuery('#calendar_fill').slideUp(); } );
});

// session checker
function check_login(){
	//var is_logged_in = $('#is_loggged_in').val();
	if(is_logged_in == 1){
		return true;
	} else {
		return false;
	}
}

function login(){
	var html = trav_loginform;
	$j.facebox(html);
}

function top_login_done(){
	$j.facebox.close();
	window.location.reload();
}	

function loginSubmit(){
	var email = $j('#loginEmail').val();
	var pass = $j('#loginPass').val();
	$j.ajax({
		type: "GET",
		url: base_url+"/member/login?ajax=1",
		dataType: "json",
		data: 'email='+email+'&password='+pass,
    	timeout: 3000,
    	error: function(){
    		$j('#facebox .content').html('There was an error.  Please try again.');
    	},		
 		success: function(msg){
 			if(msg['data']['id']){
 				is_logged_in = 1;
 				// Set some cool stuff up...
 				$j('div#welcome').html('Hi '+msg['data']['member']['first']+'! <span class="small"><a href="/public/member/home" style="text-decoration: underline;">Your Account</a>, <a href="/people/'+msg['data']['member']['screenname']+'" style="text-decoration: underline;">Your Profile</a> or <a href="/public/member/logout" style="text-decoration: underline;">Logout</a></span>');
 				memberData = msg['data']['member'];
 				eval(loginDoneExe);
 				$j('#facebox .content').html('You are logged in.<br /><br />'+loginDoneTxt);
 			} else {
 		  		// Login failed
		  		$j('#facebox .content').html(trav_loginform+'<p class="error">Username and/or password incorrect.</p>');
 			}
 		}
	});
	//return false;
}

function popBug(){
	helpWin = window.open('/public/ticket/popup','help_ticket','width=500,height=500,scrolling=0,reisze=0,status=0'); 
	if (window.focus) { helpWin.focus(); }
}

// Change external links to user the TravBar function
function activatebar()
{
	if(typeof nobar != 'undefined') { return; }
	
	var domains = new Array();
	domains['101espn.com'] = true;
	domains['toastedrav.com'] = true;
	domains['1065thearch.com'] = true;
	domains['wil92.com'] = true;		

	jQuery('a[href^="http://"]:not([class*="nobar"])').filter(function(){
     	//return this.hostname && this.hostname !== location.hostname;
     	return this.hostname && !domains[this.hostname.replace(/^(www|stage|community)\.?/i, '')]
   		}).each(function() {
     		var link = jQuery(this);
     		var url = encodeURIComponent(link.attr('href'));
     		link.attr('href', '/link?url='+url);
		});
}

// Gallery display
function inline_gallery(post_id, limit){
	if(jQuery("div#gallery"+post_id).length > 0 ){
		jQuery.ajax({
			type: "GET",
   			url: "/blogAttachment/gallery",
   			data: "ajax=1&limit="+limit+"&blogPost_id="+post_id,
   			dataType: "json",
   			success: function(msg){
     			photos = msg.data.items;
     			if(photos.length > 0){
     				div =  jQuery("div#gallery"+post_id);
     				for(var i in photos){
     					photo = photos[i];
     					div.append('<a href="/post/'+post_id+'/gallery#'+photo.id+'"><img src="http://media.bonnint.net/'+photo.image+'?filter=stl/trav_member&amp;w=75" /></a>');
     				}
     				div.append('<a href="/post/'+post_id+'/gallery" style="display: block; padding-top: 3px; text-align: right; font-size: 10px;">View this gallery. &#187;</a>');
     			}
   			}
 		});
 	}
}

// Calendar functions
function getEvents(day, cal_id){
	$j('#calendar_widget ul.dates li').removeClass('selected');
	$j('#'+day).addClass('selected');
	$j('#calendar_fill').html('');
	$j('#calendar_fill').addClass('loading');
	$j.ajax({
		type: 'GET',
		url: base_url+'/calendarEvent/day',
		dataType: 'html',
		data: 'day='+day+'&calendar_id='+cal_id,
	  	timeout: 3000,
    	error: function(){
    		$j('#calendar_fill').removeClass('loading');
    		$j('#calendar_fill').text('There was an error retrieving the events.  Please try again in a moment.');
    	},		
 		success: function(msg){
 			$j('#calendar_fill').removeClass('loading');
			$j('#calendar_fill').html(msg);
			$j('#calendar_fill').ready(function($) {
  				//$('a[rel*=facebox]').facebox()
			});		
 		}
	});
}

function eventDetails(id){
	$j.facebox('/public/calendarEvent/look/'+id);
}

// 3List javascript 
function getNewList(list_id, page, event){
	event.preventDefault();
	
	if(page == ''){
		page = $j('div#list-'+list_id+' input.page').val()
	}
	var mode = $j('div#list-'+list_id+' div.tabs a.selected').attr('rel');
	
	$j('div#list-'+list_id+' ul.posts').fadeOut('fast', function(){
		$j.ajax({
			type: 'GET',
			url: "/sectionList/index_ajax",
			dataType: 'html',
			data: "list_id="+list_id+"&mode="+mode+"&page="+page,
			error: function(){
				alert('There was an error pulling posts.');
			},
			success: function(html){
				$j('div#list-'+list_id).parent().html(html);
			}
		});	
	});
}

// Feature js
var count = new Array();
var timer = new Array();
var limit = new Array();
function change(to, feat_num){
	$j('#feature_items'+feat_num+' li').css('display', 'none');
	
	$j('#feature_index'+feat_num+' li').removeClass('selected');
	
	// Set the desired item to display
	$j('#item'+feat_num+'x'+to).css('display', 'block');
	$j('#index'+feat_num+'x'+to).addClass('selected');
}
// Timer for feature
function stop_auto(feat_num){
	clearTimeout(timer[feat_num]);
	timer[feat_num] = false;
}
function toggle_auto(feat_num){
	if(!timer[feat_num]){
		$j('#toggle_switch'+feat_num).html('Pause');
		auto(feat_num);
	} else {
		$j('#toggle_switch'+feat_num).html('Play');
		stop_auto(feat_num);
	}
}
function auto(feat_num){
	var n = count[feat_num];
	change(n, feat_num);
	if(n == limit[feat_num]){
		count[feat_num] = 0;
	} else {
		count[feat_num] = n+1;
	}
	timer[feat_num] = setTimeout(function() {auto(feat_num);}, 5000);
}

/* Now Playing */
function load_nowplaying(){
	get_nowplaying(station);
	setTimeout("load_nowplaying()", save_intval);
}

function get_nowplaying(station){
	//alert('starting...'+$j('#np_title').html());
	$j.ajax({
		type: 'GET',
		url: base_url+'/nowplaying/read',
		dataType: "json",
		data: 'station='+station,
		cache: false,
		error: function(){
			//alert('There was an error pulling the now playing data.');
		},
		success: function(msg){
			if(msg.data[0].title != current_title){
				//alert('get ready!');
				$j("#nowplaying_guts").fadeToggle("slow", function(){
					if(msg.data[0].title == '#break#'){
						msg.data[0].title = 'Coming up...more music!';
						msg.data[0].album = '';
					}
					$j('#np_title').text('"'+msg.data[0].title+'"');
					if(msg.data[0].artist == '#break#'){
						msg.data[0].artist = '';
					}
					$j('#np_artist').text('by '+msg.data[0].artist);
					$j('#np_album').text('on '+msg.data[0].album);	
					$j("#nowplaying_guts").fadeToggle("slow");				
				});
				// Reset the current_title flag.
				current_title = msg.data[0].title;
			}
		}
	});
}

function search_nowplaying(station, time){
	$j.ajax({
		type: 'GET',
		url: base_url+'/nowplaying/search',
		dataType: 'html',
		data: 'station='+station+'&time='+time,
		cache: false,
		error: function(){
			//alert('There was an error pulling the now playing search results.');
		},
		success: function(msg){
			$j("#song_search_results").slideToggle("slow", function(){
				$j('#song_search_results').html(msg);
			});
			$j("#song_search_results").slideToggle("slow");
		}
	});
}

// PopUp creation function
function popup(href, params){  
    // Defaults (don't leave it to the browser)  
    var defaultParams = {  
        "width":       "750",   // Window width  
        "height":      "500",   // Window height  
        "top":         "400",     // Y offset (in pixels) from top of screen  
        "left":        "200",     // X offset (in pixels) from left side of screen  
        "directories": "no",    // Show directories/Links bar?  
        "location":    "no",    // Show location/address bar?  
        "resizeable":  "yes",   // Make the window resizable?  
        "menubar":     "no",    // Show the menu bar?  
        "toolbar":     "no",    // Show the tool (Back button etc.) bar?  
        "scrollbars":  "no",   // Show scrollbars?  
        "status":      "no"     // Show the status bar?  
    };  
  
    var windowName = params["windowName"] || "new_window";  
  
    var i, useParams = "";  
  
    // Override defaults with custom values while we construct the params string  
    for (i in defaultParams)  
    {  
        useParams += (useParams === "") ? "" : ",";  
        useParams += i + "=";  
        useParams += params[i] || defaultParams[i];  
    }  
    
    return window.open(href, windowName, useParams);  
}