jQuery(document).ready(function(){
	jQuery("li.pollvote").mouseenter (function(){
		jQuery(this).addClass("picked");
		jQuery(this).find("div.pca-poll-clicktovote").show();
	});

	jQuery("li.pollvote").mouseleave (function(){
		jQuery(this).removeClass("picked");
		jQuery(this).find("div.pca-poll-clicktovote").hide();
	});
	
	jQuery("a#pca-login").click( function() {
		jQuery("div#pca-hidden-login-controls").css('display', 'inline');
		jQuery("a#pca-login").hide();
		jQuery("#fb-connect").hide();
		return false;
	});

	jQuery("a.share").click( function() {
		var pollid = jQuery(this).attr('name');
		jQuery("div.share-" + pollid).toggle();
		return false;
	});
	
	jQuery("li a.share").mouseover( function() {
		var pollid = jQuery(this).attr('name');
		jQuery("div.share-" + pollid).show();
		return false;
	});
	
	jQuery("li a.share").mouseleave( function() {
		var pollid = jQuery(this).attr('name');
		jQuery("div.share-" + pollid).hide();
		return false;
	});
	
	jQuery("div.pca-share-chicklets").mouseenter( function() {
		var pollid = jQuery(this).attr('name');
		jQuery("div.share-" + pollid).show();
		return false;
	});
	
	jQuery("div.pca-share-chicklets").mouseleave( function() {
		var pollid = jQuery(this).attr('name');
		jQuery("div.share-" + pollid).hide();
		return false;
	});

	jQuery(".error").hide();
	jQuery(".pollcomment").click( function() {
		// validate and process form here
			jQuery(".error").hide();
			var comment = jQuery("input#comment").val();
			if (comment === "") {
				jQuery("label#comment_error").show();
				jQuery("input#comment").focus();
				return false;
			}
			var pollid = jQuery("input#pollid").val();
			var dataString = 'pollId=' + pollid + '&comment=' + comment;
			// alert (dataString);return false;
			jQuery.ajax( {
				type :"POST",
				url :"/pca/data/addComment.jsp",
				data :dataString,
				success : function() {
					
				}
			});
			// reload comment data
			loadComments(pollid);
			return false;
	});
	jQuery(".pollvote").click( function() {
		jQuery(this).find("div.pca-poll-clicktovote").hide();
		jQuery(this).removeClass("picked");
		jQuery(this).find("div.pca-poll-status").show();

		var pollid = jQuery(this).attr('id');
		var optionid = jQuery(this).attr("name");
		
		//trigger display
		window.setTimeout( function() { hideSendingVote(pollid, optionid); }, 1000);
		
		// vote call
		jQuery.get("/pca/data/vote.jsp", {
			pollId :pollid,
			optionId :optionid
		}, function(data) {
			// TODO determine if success response
		});
		//remove ability to vote
		//not working
		jQuery('li.' + pollid + '-pollOption').removeClass("pollvote");
		jQuery('li.' + pollid + '-pollOption').unbind('click');
		jQuery('li.' + pollid + '-pollOption').unbind('mouseenter').unbind('mouseleave');
		
	});
	jQuery("input#loginbutton").click( function(event) {
		event.preventDefault();
		var username = jQuery("input#username").val();
		var password = jQuery("input#password").val();
		// login call
		jQuery.getJSON("/pca/data/login.jsp", {
			login: username,
			password: password
		}, function(data) {
			//determine if success response
			if ( data.message == "SUCCESS" )
			{
				//hide form
				//alert(data.username);
				jQuery("div#pca-header-error").hide();
				jQuery("div#pca-hidden-login-controls").hide();
				jQuery("div#pca-login-controls").hide();
				jQuery("a#loginWelcome").text("Welcome, " + data.username);
				jQuery("div#pca-logout-controls").show();
				jQuery("li#editPreferences").show();
				jQuery("div#comment-login").hide();
				jQuery("div#comment-form").show();
				jQuery("div#comment-flag").show();
				//polls page
				jQuery("li#buzzPoll-login").hide();
				jQuery("li#buzzPoll-becomeMember").hide();
				jQuery("li#buzzPoll-create").show();
			} else {
				//alert(data);
				jQuery("p#loginError").text(data.message);
				jQuery("div#pca-header-error").show();
			}
		});
		return false;
	});
	jQuery("input#logoutbutton").click( function(event) {
		event.preventDefault();
		// logout call
		jQuery.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8"});
		jQuery.getJSON("/pca/data/login.jsp", {
			action : "logout"
		}, function(data) {
			//determine if success response
			if ( data.message == "SUCCESS" )
			{
				//alert("logged out");
				//hide form
				jQuery("div#pca-header-error").hide();
				jQuery("div#pca-hidden-login-controls").hide();
				jQuery("a#pca-login").show();
				jQuery("div#pca-login-controls").show();
				jQuery("div#pca-logout-controls").hide();
				jQuery("li#editPreferences").hide();
				jQuery("div#comment-login").show();
				jQuery("div#comment-form").hide();
				jQuery("div#comment-flag").hide();
				//polls page
				jQuery("li#buzzPoll-login").show();
				jQuery("li#buzzPoll-becomeMember").show();
				jQuery("li#buzzPoll-create").hide();
			} else {
				//alert(data);
				jQuery("p#loginError").text(data.message);
				jQuery("div#pca-header-error").show();
			}
		});
		return false;
	});
	jQuery(".showcomments").click( function() {
		// show comments
		var pollid = jQuery(this).attr('id');
		jQuery("#" + pollid + "-pollcomments").show("fast");
		// show comment form
		jQuery("#" + pollid + "-commentform").show("fast");
	});
	jQuery('#pca-everyzing-search form[name="everyzing-search"] input[name="q"]').focus(function(){
		if(jQuery(this).val() == 'Search'){
			jQuery(this).val('').toggleClass('inactive');																																										
		}
	});
	jQuery('#pca-everyzing-search form[name="everyzing-search"] input[name="q"]').blur(function(){
	 if(jQuery(this).val() == ''){
		jQuery(this).val('Search').toggleClass('inactive');																																										
	 }
	});

});

function updateNowPlaying(text) {
	jQuery("h3#now-playing").html("<strong>Now Playing:&nbsp;</strong>" + text );
}

function facebook_onlogin() { 
	jQuery("div#pca-header-error").hide();
	jQuery("div#pca-hidden-login-controls").hide();
	jQuery("div#pca-login-controls").hide();
	jQuery("div#pca-logout-controls").html("Welcome, <fb:name uid='loggedinuser' useyou='false'></fb:name> <img src='http://static.ak.fbcdn.net/images/icons/favicon.gif' /><a href='#' onclick='FB.Connect.logout(function() { facebook_onlogout(); })'>Logout of Facebook</a>");
	jQuery("div#pca-logout-controls").show();
	// because this is XFBML, we need to tell Facebook to re-process the document 
	FB.XFBML.Host.parseDomTree(); 
}

function facebook_onlogout() {
	window.location = "/pca/index.jsp";
}

function loadComments(pollid) {
	//get comment data
	jQuery.getJSON("/pca/data/commentData.jsp", { pollId :pollid }, 
		function(data) {
			jQuery("#" + pollid + "-pollcomments").text("");
	        jQuery.each(data.comments, function(i,comment){
	        	jQuery("#" + pollid + "-pollcomments").append(comment.authoredDate + "<br />");
	        	jQuery("#" + pollid + "-pollcomments").append(comment.user + " says:" + comment.commentText + "<br />");
	        });
	});
	//create content
	jQuery("#" + pollid + "-pollComments").show("fast");
}

function comment(pollid, text) {
	jQuery.get("/pca/data/addComment.jsp", {
		pollId :pollid,
		comment :text
	}, function(data) {
		jQuery("#featPollContent").text(data + "Comment");
	});
}


function hideSendingVote(pollid, optionid) {
	//hide sending vote
	jQuery("div.pca-poll-status").hide();
	// indicate option voted on
	//not working
	//looks like its working now, might have been missing a style that is there now
	jQuery('li.' + pollid + '-pollWinner').addClass("picked");
	
	// hide poll text;
	jQuery("ul.pca-fan-poll-voting div.pca-poll-text-" + pollid).hide();
	jQuery("ul.pca-user-poll-voting div.pca-poll-text-" + pollid).hide();
	
	//update for fan poll
	jQuery('ul.pca-fan-poll-voting-' + pollid + ' li').addClass("pca-bar-results");
	jQuery('ul.pca-user-poll-voting-' + pollid + ' li').addClass("pca-bar-results");
	// show poll results
	jQuery("div.pca-poll-result-" + pollid).slideDown();
	
	//trigger rotation
	window.setTimeout( function() { rotateCarousel(); }, 2000);
}

function rotateCarousel() {
	var selected = jQuery("#pca-tabs").tabs('option', 'selected');
	//check if last tab
	var totalSize = jQuery(".pca-featured-poll").size() - 1;
	
	var next = 0;
	
	if ( selected != totalSize ){
		next = selected + 1;
	}

	jQuery("#pca-tabs").tabs('select', next);
}

function flashVote(pollid, category) {
	
}

//----------------------------------------------------------------------

window.onload = function( e ) {
	
	if( document.getElementById( "username" ) ) {
		document.getElementById( "username" ).onfocus = function( e ) {
			if( this.getAttribute( "value" ).toLowerCase() === "email" ) {
				this.setAttribute( "value" , "");
			}
			this.style.color = "#000";
		};
	}
	
	if( document.getElementById( "everyzing-search" ) ) {
		document.getElementById( "everyzing-search" ).onfocus = function( e ) {
			if( this.getAttribute( "value" ).toLowerCase() === "search" ) {
				this.setAttribute( "value" , "");
			}
			this.style.color = "#000";
		};
	}

	if( document.getElementById( "fake_password" ) ) {
		document.getElementById( "fake_password" ).onfocus = function( e ) {
			this.style.display = "none";
			this.setAttribute( "value" , "");
			document.getElementById( "password" ).setAttribute( "value" , "");
			document.getElementById( "password" ).style.display = "inline";
			document.getElementById( "password" ).focus();
		};
	}
	
	if( document.getElementById( "pca-header-error-close" ) ) {
		document.getElementById( "pca-header-error-close" ).onmouseup = function( e ) {
			document.getElementById( "pca-header-error" ).style.display = "none";
		};
	}
	
};

//-------

//----------------------------------------------------------------------
function isEmpty(inputStr){
// purpose : to check if an input value is empty
// input   : form value, field name for alert message
// output  : returns true if the form field is blank

	if(inputStr === null || inputStr === ""){
		return true;		
	}
	return false;	
}
//----------------------------------------------------------------------
function isEmptyMessage (fieldName) {
	// purpose : message for empty field values
	// input   : field name
	// output  : none
	alert(fieldName + " is a Required Field");
}
//----------------------------------------------------------------------
//purpose	: to check if the email is formatted
//input		: email string
//output	: returns true if the email is formatted
 
function echeck(str) {
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	
	if (lstr < 6){
	 //  alert("Invalid E-mail ID")
	   return false;
	}
	
	if (str.indexOf(at) === -1){
	 //  alert("Invalid E-mail ID")
	   return false;
	}

	if (str.indexOf(at)=== -1 || str.indexOf(at) === 0 || str.indexOf(at) === lstr){
	 //  alert("Invalid E-mail ID")
	   return false;
	}

	if (str.indexOf(dot) === -1 || str.indexOf(dot) === 0 || str.indexOf(dot) === lstr){
	 //   alert("Invalid E-mail ID")
	    return false;
	}

	if (str.indexOf(at,(lat+1)) !== -1){
	//	alert("Invalid E-mail ID")
	    return false;
	}

	if (str.substring(lat-1,lat) === dot || str.substring(lat+1,lat+2) === dot){
	//	alert("Invalid E-mail ID")
	    return false;
	}

	if (str.indexOf(dot,(lat+2)) === -1){
	 //   alert("Invalid E-mail ID")
	    return false;
	}
		
	if (str.indexOf(" ") !== -1){
	//	alert("Invalid E-mail ID")
		return false;
	}
	
	if (str.substring(ldot, lstr-1).length < 2) {
	//	alert("Invalid E-mail ID")
		return false;
	}
 	return true;			
}

/**********************************
* 
**********************************/
function errorMsgDisplay(field, msg, lastField) {
	//highlight errorfield
	alert('in errorMsgDisplay...');
	var fld = document.getElementById(field);
	if (fld !== null) {
		addClassName (fld, 'errorfield');	
	}
}

function toggleEmailRadios() {

	if (($('receiveEmail') !== null) && ($('receivePollEmail') !== null)) {
		var chkd = $('receiveEmail').checked;
		$('receivePollEmail').disabled = !(chkd);

		switch(chkd) {
			case true:	
//				$('receivePollEmail').setStyle("backgroundColor", "");
				break;
			case false:
				$('receivePollEmail').checked = chkd;
//				$('receivePollEmail').setStyle("backgroundColor", "#cdcdcd");
				break;
		}
	}
}

/*****************************
* for user-created poll preview
*****************************/
	function previewPush() {
		//urchinTracker("/createAPoll/buzzPollsPreview?category=" + document.createPollForm.category.value);
		var updateValues = "";
		//validate each field is not blank?
		var validEntries = true;
		//if ok, grab values
		var question = document.createPollForm.bpquestion.value;
		var answer1 = document.createPollForm.bpans1.value;
		var answer2 = document.createPollForm.bpans2.value;
		var answer3 = document.createPollForm.bpans3.value;
		var answer4 = document.createPollForm.bpans4.value;
		//answer3 = escapeChars(answer3);   //not required
		if (isEmpty(question) || isEmpty(answer1) || isEmpty(answer2)) {
			alert("Please enter all required fields.\n(You must have at least one question and two answers)");
			return false;
		}
		question = escapeChars(question);
		answer1 = escapeChars(answer1);
		answer2 = escapeChars(answer2);
		answer3 = escapeChars(answer3);
		answer4 = escapeChars(answer4);

/*
		var question = document.createPollForm.bpquestion.value;
		if (question.length() < 1) {
		 	alert("Error, question is a required field");
			return;
		 } else {
		  updateValues = question + ",";
		  }
		 
		 var bpans1 = document.createPollForm.bpans1.value;
		if (bpans1.length() < 1) {
		 alert("Error, that is a required field");
		 	return;
		 } else {
		  updateValues = bpans1 + ",";
		  }
*/
		 updateValues = question + "," + answer1 + "," + answer2 + "," + answer3 + "," + answer4;
		 //debug
		 //alert(updateValues);
		 
		var el = getMovieName("previewpollflash");
		el.updatePollPreview(updateValues);
}

function createPreviewPoll() {
	if ($('previewpolldiv') !== null) {
	  var previewSo = new SWFObject("/pca/flash/createPollLoader.swf", "previewpollflash", "250", "395", "#523863");
	   previewSo.addParam("allowScriptAccess", "always");
	   previewSo.addParam("wmode", "transparent");
	   previewSo.write("previewpolldiv");
		
	}
}



/*********************
* escape characters to string passing
* currently takes out links, allows for formatting
**********************/

function escapeChars(str) {
	str = str.replace(/\'/g,"&#39;"); 	 //apostrophes
	str = str.replace(/\,/g, "&#44;"); 		//commas
	str = str.replace(/\"/g, '&#34;'); 	//double quotes

	str = str.replace(/<a[^>]+>/g, ""); 	//strip out links (open)
	str = str.replace(/<\/a>/g ,""); 	//strip out links (end)
	//str = str.replace(/<.+?>/g, "");  all html (not just links)

	return str;
}




/******************
* utility scripts *
******************/
function addClassName (elem, className) {
	//first ensure something is being passed in
		if (elem !== null) 
		{
			//then ensure it refers to an element on the page
			if ($(elem) !== null)
			{ 
			    removeClassName (elem, className);
			    elem.className = (elem.className + " " + className).trim();
			}
		}
}

function removeClassName (elem, className) {
	//first ensure something is being passed in
	if (elem !== null) 
	{
		//then ensure it refers to an element on the page
		if ($(elem) !== null) 
		{
	    	elem.className = elem.className.replace(className, "").trim();
		}
	}
}

function openPopup(url, title, features) {
	var newWin = window.open(url, title, features);
	newWin.focus(); 
}
//used when we push JS into AS.. mediagallery, pollpreview...
function getMovieName(movieName) {
   	if (navigator.appName.indexOf("Microsoft") !== -1) {
   		return window[movieName];
   	} else {
   		return document[movieName];
   	} 

 }
function dropdown()
{
	var startWeek, startMonth;
	endWeek = this.document.PCAForm.mySel.value;
	startMonth = this.document.PCAForm.mySel1.value;
	window.location='/pca/polls/pollarchive.jsp?endWeek=' + endWeek + '&startMonth=' + startMonth;
}
function dropdownweek()
{
	var startWeek;
	endWeek = this.document.PCAForm.mySel.value;
	window.location='/pca/polls/buzzpollarchive.jsp?endWeek=' + endWeek;
}
function userdropdownweek()
{
	var startWeek;
	filter = this.document.PCAForm.mySel.value;
	profile = this.document.PCAForm.profile.value;
	window.location='/pca/account/profilefavorites.jsp?tab=expired&filter=' + filter + '&profileId=' + profile;
}
function dropdownmonth()
{
	var startMonth;
	startMonth = this.document.PCAForm.mySel1.value;
	window.location='/pca/monthlypollarchive.jsp?startMonth=' + startMonth;
}
function showHistory()
{
	var year;
	year = this.document.PCAForm.mySel.value;
	//window.location='/pca/history.jsp?year=' + year;
	window.location='/pca/awards/nominees/index.jsp?year=' + year;
}

//for setting a max on textareas
//from http://www.dynamicdrive.com/dynamicindex16/maxlength.htm
function ismaxlength(obj){
	var mlength = obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : "";
	if (obj.getAttribute && obj.value.length > mlength) {
		obj.value=obj.value.substring(0,mlength);
	}
}

/******************
* outbound links.. assign analytics code
**********************/
function outboundLink(url) {
	urchinTracker('/outgoing/' + url);
	window.open(url);
}
