$(document).ready(function(){
//Header Navigation Rollovers
//alert("location:"+location.pathname);

if(location.pathname == siteRoot) {
		$("div#hovermenu ul li a.nav_0").addClass("current");
	}else{
		$("div#hovermenu ul li a").each( function(index) {

				  if ($(this).attr('href').indexOf(pageCategory) > -1)
				  {
					$(this).addClass("current");
				  }
		});
	}
	
	featuredvid_links = $('a[rel=featured-link]');
	featuredvid_links.each( function( index ) {
    var link = $( this );
    link.click( function( c ) {
        c.preventDefault();
		loadVideo($(this).attr('href'));
    } );
	} );

});

function toggleFeatured() {
	var toggleObj=document.getElementById("colfeatures");
	if(toggleObj.style.display=="block") {
		toggleObj.style.display="none";
	}else{
		toggleObj.style.display="block";
	}
}

function loadVideo(id) {
	phpURL="/video_embed.php";
	phpParams="id="+id;
		$.ajax({
	    type: "POST",
	    url: phpURL,
	    data: phpParams,
	    success: function(result) {  
			//console.log("post success:"+result);
			$('#watch_topcontent').html(result);
   		},
   		error: function (xmlHttpRequest, textStatus, errorThrown) {
			//alert("post error:");
			$('#watch_topcontent').html( errorThrown );
   		}
	}); // end ajax
	return false;
}

function updateVideoListing(url,sort_param) {
	phpURL=url;
	if(sort_param=="most-recent") {
		sortHeader="MOST RECENT";
	}else if(sort_param=="top-rated") {
		sortHeader="TOP RATED";
	}else{
		if(url.indexOf('watch')!=-1) {
			sortHeader="VIDEOS A-Z";
		}else{
			sortHeader="AUDIO A-Z";
		}
	}
	phpParams="sort="+sort_param+"&";
	phpParams+=$('#sortButtonForm').serialize();
	//alert("phpParams:"+phpParams+" url:"+phpURL);
		$.ajax({
	    type: "POST",
	    url: phpURL,
	    data: phpParams,
	    success: function(result) {  
			//console.log("post success:"+result);
			$('#videoHdr').html(sortHeader);
			document.getElementById("colfeatures").style.display="none";
			$('#listing_holder').html(result);
   		},
   		error: function (xmlHttpRequest, textStatus, errorThrown) {
			//alert("post error:");
			$('#listing_holder').html( errorThrown );
   		}
	}); // end ajax
	return false;
}

function toggle(elementName) {
	var toggleObj=document.getElementById(elementName);
	if(toggleObj.style.display=="block") {
		toggleObj.style.display="none";
	}else{
		toggleObj.style.display="block";
	}
}

function toggleCommentForm() {
	var commentObj=document.getElementById("commentDisplay");
	var formObj=document.getElementById("commentsForm");
	if(formObj.style.display=="block") {
		formObj.style.display="none";
		if(commentObj.style.display=="block") {
			commentObj.style.display="none";
		}
	}else{
		$(':input','#commentsForm').each(function() {
			 var type = this.type;
			 var tag = this.tagName.toLowerCase(); // normalize case
			 // it's ok to reset the value attr of text inputs,
			 // password inputs, and textareas
			 if (type == 'text' || type == 'password' || tag == 'textarea')
			   this.value = "";
		});
		formObj.style.display="block";
		if(commentObj.style.display=="block") {
			commentObj.style.display="none";
		}
	}
}

function postComment() {
	var phpURL=$('#formComment').attr('action');
	// get form fields
	var name = $('#name').val();
	var email = $('#email').val();
	var code = $('#code').val();
	
	$('#commentError').html("");
	
	if (!name) {
		$('#commentError').html("Name is required.");
		return false;
	}
	if (!email) {
		$('#commentError').html("E-Mail is required.");
		return false;
	} 
	var emailFormat = /^\w(\.?[\w-])*@\w(\.?[\w-])*\.[a-zA-Z]{2,6}(\.[a-zA-Z]{2})?$/i;
	var eres=email.search(emailFormat);
	if(eres == -1)
	{
		$('#commentError').html("E-Mail is invalid.");
		return false;
	}
	
	phpParams=$('#formComment').serialize();
	//alert("phpParams:"+phpParams+" url:"+phpURL);
		$.ajax({
	    type: "POST",
	    url: phpURL,
	    data: phpParams,
	    success: function(result) {  
			//console.log("post success:"+result);
			var isFound =result.indexOf('id="formComment"');
			//alert("result:"+result);
			//alert("ISFOUND:"+isFound);
			if(isFound!=-1) {
				$('#commentsForm').html(result);
			}else{
				document.getElementById("commentsForm").style.display="none";
				$('#commentDisplay').html(result);
				document.getElementById("commentDisplay").style.display="block";
			}
		},
   		error: function (xmlHttpRequest, textStatus, errorThrown) {
			//alert("post error:");
			$('#commentsForm').html( errorThrown );
   		}
	}); // end ajax
	return false;
	
}

function report(id) {
	var phpURL="/comments.php";
	return false;
	phpParams="action=report&id="+id;
	//alert("phpParams:"+phpParams+" url:"+phpURL);
		$.ajax({
	    type: "POST",
	    url: phpURL,
	    data: phpParams,
	    success: function(result) {  
			//console.log("post success:"+result);
			$('#report-status').html( result );
   		},
   		error: function (xmlHttpRequest, textStatus, errorThrown) {
			//alert("post error:");
			$('#report-status').html( errorThrown );
   		}
	}); // end ajax
	return false;
	
}

function bindComments() {
	links = $('a[rel=comment-link]');
	links.each( function( index ) {
    var link = $( this );
    link.click( function( c ) {
        c.preventDefault();
		postComment();
    } );
	} );
}

function bindReporting() {

links = $('a[rel=report_link]');
	links.each( function( index ) {
    var link = $( this );
    link.click( function( c ) {
        c.preventDefault();
		report($(this).attr('href'));
    } );
	} );
}

function bindSeason() {
	links = $( 'a[rel^=season_page_link]' );
	links.each( function( index ) {
		var link = $( this );
		 link.click( function( c ) {
			c.preventDefault();
			//load and populate edit detail page form
			loadSeason($(this).attr('href'));
		} );
	} );
}


function bindRatings() {
	links = $( 'a[rel^=rating_link]' );
	links.each( function( index ) {
		var link = $( this );
		 link.click( function( c ) {
			c.preventDefault();
			//load and populate edit detail page form
			loadRating($(this).attr('href'));
		} );
	} );
}

function loadRating(url) {
	phpURL=url.split("?")[0];
	phpParams=url.split("?")[1];
	//alert("phpParams:"+phpParams+" url:"+phpURL);
		$.ajax({
	    type: "POST",
	    url: phpURL,
	    data: phpParams,
	    success: function(result) {  
			//console.log("post success:"+result);
			$('#video_rating').html(result);
   		},
   		error: function (xmlHttpRequest, textStatus, errorThrown) {
			//alert("post error:");
			$('#video_rating').html( errorThrown );
   		}
	}); // end ajax
	return false;
}


function search_go(siteRoot) {
	var search_url=document.getElementById('site_search').term.value;
	search_url=search_url.replace("/\s/","_");
	//alert("newurl:"+siteRoot+"search.php?term="+search_url);
	document.location.href=siteRoot+"search.php?term="+search_url;
	return false;
}

function toggleDownloads() {
	var socialObj=document.getElementById("download_icons");
	if(socialObj.style.display=="block") {
		socialObj.style.display="none";
	}else{
		socialObj.style.display="block";
	}
}

function bindSelect() {
	$(function(){
	$('#vidFilterSelect').customStyle();
	});
}


function saveMember(buttonObj) {
	var buttonName=buttonObj.name;
	

	phpParams=$('#member_update_form').serialize();
	
	
	$.ajax({
	    type: "POST",
	    url: siteRoot+"bpm_user_edit.php",
	    data: phpParams,
	    success: function(result) {  
			//alert("post success:"+result);
			$('#member_form').html(result);
			$('#dataDisplay').html("Member information has been updated!");
		},
   		error: function (xmlHttpRequest, textStatus, errorThrown) {
			//alert("post error:");
			$('#member_form').html( errorThrown );		
   		}
		}); // end ajax
	
}


function bindReset() {
	$("#member_reset_form").bind("submit", function(event) {
	event.preventDefault();
	updatePassword();
});
	var reset_link = $('a[rel=resetpwd]');
	reset_link.each( function( index ) {
    var link = $( this );
    link.click( function( c ) {
        c.preventDefault();
		toggle("password_form");
    } );
	} );
}

function clear_form_elements(ele) {
	 
	    $(ele).find(':input').each(function() {
	        switch(this.type) {
	            case 'password':
	            case 'select-multiple':
	            case 'select-one':
	            case 'text':
	            case 'textarea':
	                $(this).val('');
	                break;
	            case 'checkbox':
	            case 'radio':
	                this.checked = false;
	        }
	    });
	 
}

function updatePassword() {
	if($('#current').val()=="") {
		$('#resetDisplay').html("Current password is blank, please enter a value!");
	}else if($('#new').val()=="") {
		$('#resetDisplay').html("New password is blank, please enter a value!");
	}else if($('#new').val()!=$('#new_check').val()) {
		$('#resetDisplay').html("Passwords don't match!");
	}else {
			phpParams=$('#member_reset_form').serialize();
			alert("params:"+phpParams);
			$.ajax({
		    type: "POST",
		    url: siteRoot+"bpm_user_edit.php",
		    data: phpParams,
		    success: function(result) {  
				//console.log("post success:"+result);
				$('#resetDisplay').html(result);
				clear_form_elements('member_reset_form');
	   		},
	   		error: function (xmlHttpRequest, textStatus, errorThrown) {
				//alert("post error:");
				$('#resetDisplay').html( errorThrown );
	   		}
		}); // end ajax
	}
	return false;
}


function updateListing(url) {
	phpURL=url;
	videoTag=$('#vidFilterSelect').val().split("|")[0];
	phpParams="action=update_listing&channel_tag="+videoTag;
	//alert("phpParams:"+phpParams+" url:"+phpURL);
		$.ajax({
	    type: "POST",
	    url: phpURL,
	    data: phpParams,
	    success: function(result) {  
			//console.log("post success:"+result);
			$('#videoListHolder').html(result);
   		},
   		error: function (xmlHttpRequest, textStatus, errorThrown) {
			//alert("post error:");
			$('#videoListHolder').html( errorThrown );
   		}
	}); // end ajax
	return false;
}

function gotoChannel() {
	channelURL=$('#vidFilterSelect').val().split("|")[1];
	window.location=channelURL;
	return;
}

function removeHTMLTags(elementName){
 	if(document.getElementById && document.getElementById(elementName)){
 		var strInputCode = document.getElementById(elementName).innerHTML;
 		/* 
  			This line is optional, it replaces escaped brackets with real ones, 
  			i.e. < is replaced with < and > is replaced with >
 		*/	
 	 	strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
 		 	return (p1 == "lt")? "<" : ">";
 		});
 		//remove all hot links
 		var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
 		var extraTextPos=strTagStrippedText.lastIndexOf("http");
 		var extraTextStrip=strTagStrippedText.substring(0,extraTextPos);
  		//var strTagStrippedText = strInputCode.replace(/<(?!\/?a(?=>|\s.*>))\/?.*?>/g, "");
 		
  		document.getElementById("twitterItem").innerHTML=extraTextStrip.substring(0,142);	
   	}	
}

function loadSeason(hrefURL){
	if (typeof asynchronous == 'undefined') asynchronous = true;
	phpURL=hrefURL.split("?")[0];
	phpParams=hrefURL.split("?")[1];
	//alert("loadform:"+hrefURL);
	$.ajax({
	    type: "POST",
	    url: phpURL,
	    data: phpParams,
	    success: function(result) {  
			//alert("post success:");
			$('#rich_text_holder').html(result);
   		},
   		error: function (xmlHttpRequest, textStatus, errorThrown) {
			//alert("post error:");
			$('#rich_text_holder').html( errorThrown );
   		}
	}); // end ajax
	return false;

}

(function($){
 $.fn.extend({
 
 	customStyle : function(options) {
	  if(!$.browser.msie || ($.browser.msie&&$.browser.version>6)){
	  return this.each(function() {
	  
			var currentSelected = $(this).find(':selected');
			$(this).after('<span class="customStyleSelectBox"><span class="customStyleSelectBoxInner">'+currentSelected.text()+'</span></span>').css({position:'absolute', opacity:0,fontSize:$(this).next().css('font-size')});
			var selectBoxSpan = $(this).next();
			var selectBoxWidth = parseInt($(this).width()) - parseInt(selectBoxSpan.css('padding-left')) -parseInt(selectBoxSpan.css('padding-right'));			
			var selectBoxSpanInner = selectBoxSpan.find(':first-child');
			selectBoxSpan.css({display:'inline-block'});
			selectBoxSpanInner.css({width:selectBoxWidth, display:'inline-block'});
			var selectBoxHeight = parseInt(selectBoxSpan.height()) + parseInt(selectBoxSpan.css('padding-top')) + parseInt(selectBoxSpan.css('padding-bottom'));
			$(this).height(selectBoxHeight).change(function(){
				//selectBoxSpanInner.text($(this).val()).parent().addClass('changed');
				selectBoxSpanInner.text($('option:selected',this).text()).parent().addClass('changed');
			});
			
	  });
	  }
	}
 });
})(jQuery);
