//Global variables--------------------------------------------------------------
var ww = 0;
var hh = 0;
var pTag = "";
var nTag = "";

var formatOptions = null;
var nowPlaying = null;

//form validation---------------------------------------------------------------
function updateTips(t,s){
	if ( s ){
		//$(s).html(t);
	}else{		
		//$('#formInstructions').html(t);
	}		
}	


function checkLength(o,n,min,max,s) {

	if ( o.val().length > max || o.val().length < min ) {
		o.addClass('validationError');
		updateTips("<span class=\"error\">Length of " + n + " must be between "+min+" and "+max+".</span>",s);
		return false;
	} else {
		return true;
	}

}

function checkRegexp(o,regexp,n,s) {
	if ( !( regexp.test( o.val() ) ) ) {
		o.addClass('validationError');
		updateTips("<span class=\"error\">"+n+"</span>",s);
		return false;
	} else {
		return true;
	}
}


//onSelection-------------------------------------------------------------------
function onSelection(){
	$('#content_middle').animate({opacity:0.1}, 200,
		function(){
			$.get('index.php?task=filter_archive&section='+$('#archiveType').val()+'&category='+$('#category').val()+'&author='+$('#author').val()+'&date='+$('#date').val(),
				function(res){
					$('#content_middle').html(res);
					bindContentEvent();
					$('#content_middle').animate({opacity:1.0}, 200);
				}
			);
		}
	);
}

//search archives---------------------------------------------------------------
function searchArchives(){
	if ( term = $('#typebox').val() ){
		if ( term.length > 3 ){
			$('#content_middle').animate({opacity:0.1}, 200,
				function(){			
					$.get('index.php?task=search_streams&searchfor='+term+'&section='+$('#archiveType').val(),
						function(res){
							$('#content_middle').html(res);
							bindContentEvent();
							$('#content_middle').animate({opacity:1.0}, 200);
						}
					);
				}
			);
		}else{
			alert('to short');
		}
	}else{
		alert('no search term');
	}
}

function pagedQuery(page){
	$('#content_middle').animate({opacity:0.1}, 200,
		function(){
			$.get('index.php?task=pagedquery&page='+page,
				function(res){
					$('#content_middle').html(res);
					bindContentEvent();
					$('#content_middle').animate({opacity:1.0}, 200);
				}
			);
		}
	);
}

function pagedLive(page){
	$('#search_results').animate({opacity:0.1}, 200,
		function(){
			$.get('index.php?task=pagedlive&page='+page,
				function(res){
					$('#search_results').html(res);
					bindContentEvent();
					$('#search_results').animate({opacity:1.0}, 200);
				}
			);
		}
	);
}


//show player-------------------------------------------------------------------
function showPlayerOptions(){
    $('#archiveContent').slideUp(250,
    	function(){
    		$('#searchContent').slideUp(250,
    			function(){
					$('.bandWidthOption').each(
						function(){
							$('.bandWidthOption').hover(
								function(){$(this).addClass('highLight');},
								function(){$(this).removeClass('highLight');}
							);
							$(this).click(
								function(){
									$('.bwSelected').removeClass('bwSelected');
									$(this).addClass('bwSelected');
									$.getJSON('index.php?task=live_descriptor&uid='+liveID+'&bw='+$(this).attr('title'),
										function (res){
											if (res.status){
												nowPlaying = res.clip;
												loadPlayer('rtmp://cp132513.edgefcs.net/ondemand/');
											}else{
												alert('invalid descriptor');
											}
										}
									);
								}
							);
						}
					);
					$('#mediaSelection').slideDown(200);
				}
			);
    	}
	);
}
//play stream-------------------------------------------------------------------
function loadPlayer(u){
	
	var ncu = u?u:'rtmp://cp132513.edgefcs.net/ondemand/';
	$('#archiveContent').slideUp(250,
    	function(){
    		$('#searchContent').slideUp(250,
    			function(){
					flowplayer('vid_holder', 
							{
								src:"swfs/flowplayer.commercial-3.1.5.swf", 'wmode': 'opaque', 'width': '641', 'height': '360', 'AllowScriptAccess': 'always'
							},
							{
								key: '#@a38677a85f6f674c238',
								plugins: {
									rtmp: {
										url: 'swfs/flowplayer.rtmp-3.1.3.swf',
										netConnectionUrl: ncu
										
									},
									audio:{ 
										url: 'swfs/flowplayer.audio-3.1.2.swf' 
									},    					
									controls: {
										'autoHide': 'always',
										'bottom': '8',
										'padding': '1%',
										'width': '98%',
										'volumeSliderGradient': 'none',
										'progressColor': '#854717',
										'buttonOverColor': '#728B94',
										'volumeSliderColor': '#000000',
										'buttonColor': '#380000',
										'timeColor': '#ffffff',
										'timeBgColor': '#360000',
										'bufferGradient': 'none',
										'borderRadius': '8px',
										'progressGradient': 'none',
										'backgroundColor': '#a220700',
										'durationColor': '#ffffff',
										'backgroundGradient': [0.2,0.1,0,0,0],
										'sliderColor': '#000000',
										'bufferColor': '#220000',
										'sliderGradient': 'none',
										'tooltipTextColor': '#ffffff',
										'tooltipColor': '#360000',
										'height': '24',
										'opacity': '0.8'
									}
								},
								clip: nowPlaying
							}
						);
				}
			);
		}		
    );
}

function fetchStreamInfo(slink){
	$('#liveForm').slideUp(300);	
	$('#vid_holder').html('');
	$('#mediaSelection').css('display', 'none');
	$('#mediaOptions').html('');

	if ( slink.lastIndexOf('/') > -1 ){
		slink = slink.substr(slink.lastIndexOf('/')+1);
	}
	$.getJSON('index.php?task=streaminfo&'+slink,
		function(res){
			if ( res.status ){
				$('#clipDescription').html('<span>Title:&nbsp;</span>'+res.title+'&nbsp;<br /><span>Description:&nbsp;</span>'+res.description);
				$('#col1').load('index.php?task=related_video&type='+res.type+'&uid='+res.uid,
					function(){
						$(this).find('.mediaRef').each(
							function(){
								$(this).bind('click',function(evt){evt.preventDefault();fetchStreamInfo($(this).attr('href'));});
								$(this).bind('mouseenter',
									function(){
										if ( img = $(this).find('img') ){
											if ( src = img.attr('src') ){
												img.attr('src', src.replace(/_button./g, "_rollover."));
											}
										}
									}
								);
								$(this).bind('mouseleave',
									function(){
										if ( img = $(this).find('img') ){
											if ( src = img.attr('src') ){
												img.attr('src', src.replace(/_rollover./g, "_button."));
											}
										}
									}
								);								
							}
						);
					}
				);
				$('#col2').load('index.php?task=related_audio&type='+res.type+'&uid='+res.uid,
					function(){
						$(this).find('.mediaRef').each(
							function(){
								$(this).bind('click',function(evt){evt.preventDefault();fetchStreamInfo($(this).attr('href'));});
								$(this).bind('mouseenter',
									function(){
										if ( img = $(this).find('img') ){
											if ( src = img.attr('src') ){
												img.attr('src', src.replace(/_button./g, "_rollover."));
											}
										}
									}
								);
								$(this).bind('mouseleave',
									function(){
										if ( img = $(this).find('img') ){
											if ( src = img.attr('src') ){
												img.attr('src', src.replace(/_rollover./g, "_button."));
											}
										}
									}
								);								
							}
						);
					}
				);
				if ( res.type == 'audio' ){
					if ( res.items.length == 1 ){
						nowPlaying = {url:res.items[0].url, autoPlay:true, autoBuffering:true};
						$('#tag_holder').fadeOut(160,
							function(){
								loadPlayer();
								$('#vid_holder').fadeIn(160);
							}
						);
					}					
				}else{
					if ( res.items.length == 1){
						nowPlaying = {url:res.items[0].url, autoPlay:true, autoBuffering:true, provider:'rtmp'};
						$('#tag_holder').fadeOut(160,
							function(){
								loadPlayer();
								$('#vid_holder').fadeIn(160);
							}
						);
					}else{
						formatOptions = new Array();
						for ( i=0; i<res.items.length; ++i ){
							formatOptions.push({url:res.items[i].url, autoPlay:true, autoBuffering:true, provider:'rtmp'});
							if ( res.items[i].url.lastIndexOf('_hd.') > -1 ){ 
								$('#mediaOptions').append($('<span class="bandWidthOption" title="'+ (formatOptions.length-1) +'">High</span>'));
							}else{
								$('#mediaOptions').append($('<span class="bandWidthOption" title="'+ (formatOptions.length-1) +'">Medium</span>'));
							}							
						}
						$('#mediaOptions :first').css('margin-left',240);
						$('#tag_holder').fadeOut(160,
							function(){
								showPlayerOptions();
								$('#vid_holder').fadeIn(160);
							}
						);
					}
				}
			}else{
				alert('error');
			}
		}
	);
}

//bind events to content elements-----------------------------------------------
function bindContentEvent(){
	$('#category').change(function(){onSelection();});
	$('#author').change(function(){onSelection();});
	$('#date').change(function(){onSelection();});
	$('#searchbt').click(function(){searchArchives();});

	$('.mediaRef').unbind('mouseenter');
	$('.mediaRef').unbind('mouseleave');
	$('.mediaRef').unbind('click');
	$('.mediaRef').bind('click',function(evt){evt.preventDefault();fetchStreamInfo($(this).attr('href'));});
	
	$('.mediaRef').bind('mouseenter',
		function(){
			if ( img = $(this).find('img') ){
				if ( src = img.attr('src') ){
					img.attr('src', src.replace(/_button./g, "_rollover."));
				}
			}
		}
	);
	$('.mediaRef').bind('mouseleave',
		function(){
			if ( img = $(this).find('img') ){
				if ( src = img.attr('src') ){
					img.attr('src', src.replace(/_rollover./g, "_button."));
				}
			}
		}
	);
	
	$('.hasToolTip').tooltip({ 
		position: "center right", 
		offset: [12, 12],
		
		opacity: 0.9,
		tip: '.tooltip'
	});	
}

//mainRotator-------------------------------------------------------------------
function mainRotator(){
	$('#vid_holder').fadeOut(120,
		function(){
			$('#vid_holder').html('');
			$('#tag_holder').css('display', 'none');
			$.get('index.php?task=rotator_items',
				function(res){
					$('#tag_holder').html(res);
					$('#tag_holder').fadeIn(400,
						function(){
							$("#mainRotator").rotator({ms:7000});
						}
					);
				}
			);
		}
	);
	
}

//validateContact---------------------------------------------------------------
function validateContact(){
	var bValid = true;
	$('.validationError').removeClass('validationError');

	//validate full name and mainemail
	bValid = bValid && checkLength($('#viewerName'),"Name",3,45, '#loginStatus');
	bValid = bValid && checkRegexp($('#viewerEmail'),/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. user@streamingmemorials.com", '#loginStatus');
	bValid = bValid && checkLength($('#viewerCountry'),"Country",2,45, '#loginStatus');
	bValid = bValid && checkLength($('#viewerState'),"State/Province",2,45, '#loginStatus');
	bValid = bValid && checkLength($('#viewerQuestion'),"Question",8,1024, '#loginStatus');
			
	if ( bValid ){
		$.getJSON('index.php?task=mailit&target='+$('#contactTarget').val()+'&name='+$('#viewerName').val()+'&email='+$('#viewerEmail').val()+'&country='+$('#viewerCountry').val()+'&state='+$('#viewerState').val()+'&question='+$('#viewerQuestion').val(),
			function(res){
				if ( res.status ){
					$('#viewerName').val('');
					$('#viewerEmail').val('');
					$('#viewerCountry').val('');
					$('#viewerState').val('');
					$('#viewerQuestion').val('');
					
					$('#contactForm').slideUp(300);
				}else{
					alert(res.statusText);
				}
			}
		);
	}
}

//validateLiveForm--------------------------------------------------------------
function validateLiveForm(){
	var bValid = true;
	$('.validationError').removeClass('validationError');

	//validate full name and mainemail
	bValid = bValid && checkLength($('#qaName'),"Name",3,45, '#loginStatus');
	bValid = bValid && checkRegexp($('#qaEmail'),/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. user@streamingmemorials.com", '#loginStatus');
	bValid = bValid && checkLength($('#qaCountry'),"Country",2,45, '#loginStatus');
	bValid = bValid && checkLength($('#qaState'),"State/Province",2,45, '#loginStatus');
	bValid = bValid && checkLength($('#qaQuestion'),"Question",8,1024, '#loginStatus');
			
	if ( bValid ){
		$.getJSON('index.php?task=mailit&target='+$('#qaTarget').val()+'&name='+$('#qaName').val()+'&email='+$('#qaEmail').val()+'&country='+$('#qaCountry').val()+'&state='+$('#qaState').val()+'&question='+$('#qaQuestion').val(),
			function(res){
				if ( res.status ){
					$('#qaName').val('');
					$('#qaEmail').val('');
					$('#qaCountry').val('');
					$('#qaState').val('');
					$('#qaQuestion').val('');
					
					$('#liveForm').slideUp(300);										
				}else{
					alert(resstatusText);
				}
			}
		);
	}
}

//showContactForm---------------------------------------------------------------
function showContactForm(Live){
	if ( $('#contactForm').css('display') == 'none' ){
		$('#contactForm').slideDown(300);
	}
}

function showQaForm(Live){
	if ( $('#liveForm').css('display') == 'none' ){
		$('#liveForm').slideDown(300);
	}
}


function livePlayerReady(){
	$('#tag_holder').fadeOut(160,
		function(){
			$('#vid_holder').html('');
			$('#mediaSelection').css('display', 'none');
			$('#mediaOptions').html('<span class="bandWidthOption" style="margin-left:200px;" title="HighBw">High</span><span class="bandWidthOption" title="MediumBw">Medium</span><span class="bandWidthOption" title="LowBw">Audio Only</span>');
			$('#clipDescription').html('<span onClick="showQaForm(true)" style="cursor:pointer;">click here to send question</span>');
			showPlayerOptions();
			$('#vid_holder').fadeIn(160);
		}
	);
}

//execute search----------------------------------------------------------------
function executeSearch(){
	$.get('index.php?task=search&term='+$('#search').val(),
		function(res){
			$('#search_results').html(res);
			bindContentEvent();
			if ( $('#searchContent').css('display') == 'none' ){
				$('#searchContent').slideDown(200);
			}
		}
	);
}

//------------------------------------------------------------------------------
$(document).ready(
	function(){
		ww = window.innerWidth?window.innerWidth:document.documentElement.clientWidth;
		hh = window.innerHeight?window.innerHeight:document.documentElement.clientHeight;
		bindContentEvent();
		
		$('#contactUs').click(
			function(evt){
				evt.preventDefault();
				showContactForm();
			}
		);
		
		$('.liveFormCtr').hover(
			function(){$(this).addClass('highLight');},
			function(){$(this).removeClass('highLight');}
		);
		
		$('.liveFormCtr').click(
			function(){
				if ( $(this).html() == 'Close' ){
					$('#qaName').val('');
					$('#qaEmail').val('');
					$('#qaCountry').val('');
					$('#qaState').val('');
					$('#qaQuestion').val('');
					
					$('#liveForm').slideUp(200);					
				}else{
					validateLiveForm();
				}
			}
		);
		
		$('#go').click(
			function(){
				var term = "";
				if ( term = $('#search').val() ){
					if ( term.length > 3 ){
						$('li.current').removeClass('current');
						if ( $('#archiveContent').css('display') == 'block' ){
							$('#archiveContent').slideUp(200,
								function(){
									executeSearch();
								}
							);							
						}else{
							executeSearch();
						}
					}
				}
			}
		);
		
		$('.contactCtr').hover(
			function(){$(this).addClass('highLight');},
			function(){$(this).removeClass('highLight');}
		);
		
		$('.contactCtr').click(
			function(){
				if ( $(this).html() == 'Close' ){
					$('#viewerName').val('');
					$('#viewerEmail').val('');
					$('#viewerCountry').val('');
					$('#viewerState').val('');
					$('#viewerQuestion').val('');
					
					$('#contactForm').slideUp(200);					
				}else{
					validateContact();
				}
			}
		);
		
		if ( liveIn == -1 ){
			livePlayerReady();
		}else{
			mainRotator();
		}
	
    	$("#bannerRotation").rotator({ms:90000});
    	
		$('#liveStream').click(
			function(evt){
				evt.preventDefault();
				$.get('index.php?task=islive',
					function(res){
						if ( res.liveIn == -1 ){
							livePlayerReady();
						}else{
							$.get('index.php?task=live_archive',
								function(res){
									$('#search_results').html(res);
									bindContentEvent();									
									$('#searchContent').slideDown(200);
								}
							);
						}
					}
				);
			}
		);
		
		$('.modHref').click(
			function(evt){
				evt.preventDefault();
				if ( $('#searchContent').css('display') != 'none' ){
					$('#searchContent').slideUp(200);
				}				
				$('#clipDescription').html('');
				$('li.current').removeClass('current');
				$(this).parent().addClass('current');
				if ( $(this).attr('href') == 'home' ){
					$('#archiveContent').css('opacity',0.1);  				
					$('#archiveContent').slideUp(200,
						function(){
							if ( liveIn == -1 ){
								livePlayerReady();
							}else{
								$('#mediaSelection').slideUp(200,
									function(){
										mainRotator();
									}
								);
							}
						}
					);
				}else if ( $(this).attr('href') == 'podcasts' ){
					$('#mediaSelection').slideUp(200);
					$('#archiveContent').css('opacity',0.1);  				
					$('#archiveContent').slideUp(200);
					$('#vid_holder').fadeOut(200,
						function(){
							$('#vid_holder').html('');
							$('#tag_holder').load('index.php?task=podcasts',
								function(){
									$('.listHeader').click(
										function(){
											nTag = $(this).attr('title');
											if ( nTag == pTag ){
												$('#'+pTag).slideUp(200,
													function(){
														pTag = '';
													}
												);
											}else{
												if ( pTag && $('#'+pTag).css('display') == 'block' ){
													$('#'+pTag).slideUp(200,
														function(){
															$('#'+nTag).slideDown(200,
																function(){
																	pTag = nTag;
																}
															);
														}
													);
												}else{
													$('#'+nTag).slideDown(200,
														function(){
															pTag = nTag;
														}
													);
												}
											}
										}
									);
									$('#tag_holder').fadeIn(200);
								}
							)
						}
					);
				}else{
					$('#archiveContent').css('opacity',0.1);
					$.get('index.php?task=load_module&mod='+$('li.current>a').attr('href'),
						function(res){
							$('#archiveContent').html(res);
							bindContentEvent();
							$('#archiveContent').slideDown(200,
								function(){
									$('#archiveContent').animate({opacity:1.0}, 200);
								}
							);
						}
					);
				}
			}
		);		
    }
);

