// TODO: Exit survey

/********** GLOBAL VARIABLES ************/

var curPollIdx = 0;

/********** DOCUMENT READY HANDLERS *************/

$(document).ready(function () {
	// Get latest tweet for twitter balloon
	getLatestTweet();

	// Set up resource modal dialog
	$("#resourceModal").dialog({
		modal: true,
		width: 800,
		height: 840,
		autoOpen: false,
		closeText: "X",
		show: "fade",
		hide: "fade",
		dialogClass: "resourceModal",
		open: function (event, ui) {
			Cufon.replace(".resourceModal .ui-dialog-title", { fontFamily: "DINReg" });
		},
		beforeclose: function (event, ui) {
			$("#resourceModalIFrame").attr("src", "");
		}
	});

	$("#resourceRegistrationDialog").dialog({
		modal: true,
		width: 500,
		height: 342,
		autoOpen: false,
		closeText: "X",
		show: "fade",
		hide: "fade",
		dialogClass: "registrationDialog",
		beforeclose: function (event, ui) {
			$("#resourceRegistrationIFrame").attr("src", "");
		}
	});

	//bindClickExitChecks();
	//$(document).ajaxComplete(bindClickExitChecks); // To properly detect exits from links loaded via AJAX.
	
	//position footer links
	var footerWidth = $("#footerLinks").width();
	$("#footerLinks").css({
    "margin-left" : -(footerWidth / 2),
    "left" : "50%"
  }).show();
  
  
  //subscribe text box enter key press
  $("#txtSubscribe").keypress(function (e) {
        if (e.which == 13) {
            if (IsValidEmail(this.value)) {
                $.get("SubscribeNewsletter.aspx?email=" + this.value + "&v=" + $("#v1").val(), function(){
                  $("#txtSubscribe").fadeOut("fast", function(){
                    $("#SubscribeMsg, #SubscribeSubmit").fadeIn("fast");
                  });
                });
            }
        }
        else{
          $("#v1").val("toKen23!");
        }
    });
    
  $("#SubscribeSubmit").click(function(e){
    e.preventDefault();
    var Value = $("#txtSubscribe").val();
    if (IsValidEmail(Value)) {
          $.get("SubscribeNewsletter.aspx?email=" + Value + "&v=" + $("#v1").val(), function(){
            $("#txtSubscribe").fadeOut("fast", function(){
              $("#SubscribeMsg, #SubscribeSubmit").fadeIn("fast");
            });
          });
      }
  });
    
  //hook up watermark events
    $(".watermark").focus(function () {
        if (this.value == this.name) {
            this.value = "";
        }
    });
    $(".watermark").blur(function () {
        if (this.value == "") {
            this.value = this.name;
        }
    });
    

});

default_docready = function () {
	// TODO: Module buttons
	$("#globalNavHome a:first").addClass("on");

	var carouselID = $("#carouselIDCntnr input:hidden:first").val();
	var segment = $("#carouselIDCntnr input:hidden:eq(1)").val();

	// Check for direct link
	var qs = $.jqURL.qs({ ret: "object" });
	var slideName = "slide1";
	if (qs.slide != null) {
		slideName = qs.slide;
	}

	// Carousel SWF
	var flashvars = {
		xmlPath: "/handlers/SegmentCarouselXml.ashx?id=" + carouselID.toString() + "%26segment=" + segment,
		startName: slideName,
		headerCaption: $("#flashtitle").html()
	};
	
	var params = {
		quality: "high",
		play: "true",
		loop: "true",
		scale: "showall",
		wmode: "transparent",
		devicefont: "false",
		bgcolor: "#ffffff",
		menu: "true",
		allowfullscreen: "false",
		allowscriptaccess: "sameDomain"
	};
	var attributes = {};
	swfobject.embedSWF("/flash/carousel.swf", "homeCarousel", "900", "340", "10.0.0", "", flashvars, params, attributes);
	
	// Segment dropdown
	$("#SegmentParent").hover(
    function(){
        $(this).find("ul").show();
    },
    function(){
        $(this).find("ul").hide();
    }
  );
  
  // Bottom carousel
  var FloatingContainer = $("#homeModuleCntnr .floatingCntnr");
  var CurrentCount = 3;
  var ModuleCount = $(".homeModule").length;
  $("#homeModuleNext").click(function(e){
    e.preventDefault();
    if(CurrentCount != ModuleCount){
      FloatingContainer.animate({left : "-=285"});
      CurrentCount++;
    }
  });
  $("#homeModulePrev").click(function(e){
    e.preventDefault();
    if(CurrentCount != 3){
      FloatingContainer.animate({left : "+=285"});
      CurrentCount--;
    }
  });
  
  $(".homeModule").hover(
    function(){
      $(this).find(".slideDownBg, .slideDownContent").slideDown("fast");
    },
    function(){
      $(this).find(".slideDownBg, .slideDownContent").slideUp("fast");
    }
  );
}

blogs_docready = function () {
	$("#blogsSiteNavLink").addClass("on");

	// Get latest tweets for sidebar box
	var numTweets = $("#hiddenFieldCntnr input:hidden:first").val();
	getTwitterBoxLatestTweets(numTweets);

	// Load poll
	var pollCollID = $("#hiddenFieldCntnr input:hidden:eq(1)").val();
	loadPoll(pollCollID);
}

resourcelib_docready = function () {
	$("#resourceLibrarySiteNavLink").addClass("on");
	styleResourceLibraryDropDowns();

	// Load poll
	var pollCollID = $("#hiddenFieldCntnr input:hidden:first").val();
	loadPoll(pollCollID);
}

resourceviewer_docready = function () {
	$("#resourceLibrarySiteNavLink").addClass("on");

	$(".resourceLink").bind("click", function () {
		if (pageTracker != null) {
			pageTracker._trackEvent($("#hidEventCategory").val(), $("#hidEventAction").val(), $("#hidEventLabel").val());
		}
		return true;
	});

	// Load poll
	var pollCollID = $("#hiddenFieldCntnr input:hidden:first").val();
	loadPoll(pollCollID);
	if ($("#commentList span").length == 0) {
		__doPostBack('ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$hypPostComment', '')
	}
}

resourceviewermodal_ready = function () {
	if ($("#commentList span").length == 0) {
		__doPostBack('hypPostComment', '')
	}
	// Since videos and podcasts are auto-play, track the event on frame load
	if ($("#hidEventCategory").val() == "Video" || $("#hidEventCategory").val() == "Audio Podcast") {
		pageTracker._trackEvent($("#hidEventCategory").val(), $("#hidEventAction").val(), $("#hidEventLabel").val());
	}

	$(".resourceLink").bind("click", function () {
		if (pageTracker != null) {
			pageTracker._trackEvent($("#hidEventCategory").val(), $("#hidEventAction").val(), $("#hidEventLabel").val());
		}
		return true;
	});
}

registrationform_ready = function () {
	$("#ResourceID").val($("#hidResourceID").val());
}

events_docready = function () {
	$("#eventsSiteNavLink").addClass("on");
	styleEventDropDowns();

	// Get latest tweets for sidebar box
	var numTweets = $("#hiddenFieldCntnr input:hidden:first").val();
	getTwitterBoxLatestTweets(numTweets);

	// Load poll
	var pollCollID = $("#hiddenFieldCntnr input:hidden:eq(1)").val();
	loadPoll(pollCollID);
}

event_docready = function () {
	$("#eventsSiteNavLink").addClass("on");

	// Get latest tweets for sidebar box
	var numTweets = $("#hiddenFieldCntnr input:hidden:first").val();
	getTwitterBoxLatestTweets(numTweets);

	// Load poll
	var pollCollID = $("#hiddenFieldCntnr input:hidden:eq(1)").val();
	loadPoll(pollCollID);
}

contactus_docready = function () {
	$("#globalNavContactUs a:first").addClass("on");

	// Get latest tweets for sidebar box
	var numTweets = $("#hiddenFieldCntnr input:hidden:first").val();
	getTwitterBoxLatestTweets(numTweets);

	// Load poll
	var pollCollID = $("#hiddenFieldCntnr input:hidden:eq(1)").val();
	loadPoll(pollCollID);
}

searchresults_docready = function () {
	// Load poll
	var pollCollID = $("#hiddenFieldCntnr input:hidden:first").val();
	loadPoll(pollCollID);
}

rss_docready = function () {
	// Get latest tweets for sidebar box
	var numTweets = $("#hiddenFieldCntnr input:hidden:first").val();
	getTwitterBoxLatestTweets(numTweets);

	// Load poll
	var pollCollID = $("#hiddenFieldCntnr input:hidden:eq(1)").val();
	loadPoll(pollCollID);
}

error_docready = function () {
	// Load poll
	var pollCollID = $("#hiddenFieldCntnr input:hidden:first").val();
	loadPoll(pollCollID);
}

standalonepollpage_docready = function () {
	for (var i = 1; i <= 3; i++) {
		$("#poll" + i + "IFrame").attr("src", "/PollIFrame.aspx?collid=" + $("#hiddenInputCntnr input:hidden:eq(" + (i - 1).toString() + ")").val());
	}
	$("#pollAgainLink").bind("click", function () {
		$("#pollCntnr iframe").each(function () {
			$(this).attr("src", $(this).attr("src"));
		});
		return false;
	});
}

polliframe_docready = function () {
	// Load poll
	var pollCollID = $("#hiddenFieldCntnr input:hidden:first").val();
	loadPoll(pollCollID);
}

/**************** EXIT POPUP ******************/

//DJW - DISABLED EXIT POPUP PER CLIENT REQUEST 5/12/2010

//var leaving = true;
//window.onbeforeunload = showSiteExitPopup;

//function bindClickExitChecks() {
//    $("a").unbind("click", exitCheck).bind("click", exitCheck); // Unbind first to prevent multiple bindings on ajaxComplete to existing <a> tags
//}

//function exitCheck(e) {
//    var targ;
//    if (!e) var e = window.event;
//    if (e.target) targ = e.target;
//    else if (e.srcElement) targ = e.srcElement;
//    if (targ.nodeType == 3) // defeat Safari bug
//        targ = targ.parentNode;
//    checkUrl(targ.href);
//}

//function checkUrl(url) {
//    leaving = (url != null && url.indexOf("http://") > -1 && url.indexOf("pbconnect.com") == -1 && url.indexOf("hsrclients") == -1);
//}

//function showSiteExitPopup() {
//    if (leaving) {
//        if (readCookie("PB_ExitSurvey") == null) {
//            window.open("/ExitSurvey.aspx", "exitsurvey", "status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,width=524,height=700,scrollbars=1");
//            createCookie("PB_ExitSurvey", "1", 360);
//        }
//    }
//}

/************** RESOURCE LIBRARY FUNCTIONS ****************/

styleResourceLibraryDropDowns = function () {
	// Style category and topic dropdowns
	if (!$(".newListSelected")[0]) {
		$(".resourceLibraryCategory:first").sSelect().change(function () {
			var val = $(this).getSetSSValue();
			createCookie("resource_category", val);
			$(".resourceLibraryCategory:first").val(val).trigger("select");
		});
		$(".resourceLibraryTopic:first").sSelect().change(function () {
			var val = $(this).getSetSSValue();
			createCookie("resource_topic", val);
			$(".resourceLibraryTopic:first").val(val).trigger("select");
		});
	}
}

viewResource = function (id) {
	$("#resourceModalIFrame").attr("src", "/ResourceViewerModal.aspx?id=" + id);
	$("#resourceModal").dialog("open");
}

viewAnotherResource = function (id) {
  window.location.href = "/ResourceViewerModal.aspx?id=" + id;
 }

viewArticle = function (url) {
  window.parent.location.href = url;
}

cvRecommendLink_Validate = function (source, args) {
	var id = $("#resourceIDCntnr input:hidden:first").val();
	if (readCookie("r" + id.toString()) != null) {
		args.IsValid = false;
	}
	else {
		args.IsValid = true;
	}
}

registerForResource = function (id) {
	// Embed the ID
	$(parent.document).find("#hidResourceRegistrationID").val(id);
	// Clever trick for closing the dialog from a click inside the iframe: http://feelitfresh.com/web20/jquery-ui-dialog-close/
	var modalTrigger = $(parent.document).find("#resourceModalRegister");
	if (modalTrigger == null) // If we're not inside the modal resource dialog, just fade the registration dialog in.
		showRegistrationDialog(id);
	else
		modalTrigger.trigger("click"); // This click will also handle showing the registration dialog
}

fullRegisterForResource = function (id) {
	showRegistrationDialog(id);
}

showRegistrationDialog = function (id) {
	if (id == null)
		id = $("#hidResourceRegistrationID").val();
	$("#resourceRegistrationIFrame").attr("src", "/RegistrationForm.aspx?rid=" + id);
	$("#resourceRegistrationDialog").dialog("open");
}

validateRegistrationDialog = function () {
	$("span.errorMessage").remove();
	$(".registrationCell input[type='text']").each(function () {
		$(this).removeClass("error");
		if ($.trim($(this).val()) == "") {
			$(this).addClass("error");
		}
		else if ($(this).hasClass("emailField") && !/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test($.trim($(this).val()))) {
			$(this).addClass("error");
			$("<span>").addClass("errorMessage").text("Invalid e-mail address.").appendTo($(this).parent());
		}
	});
	return ($(".error").length == 0);
}

/************** EVENT FUNCTIONS *******************/

styleEventDropDowns = function () {
	// Style category and topic dropdowns
	if (!$(".newListSelected")[0]) {
		$(".eventCategory:first").sSelect().change(function () {
			var val = $(this).getSetSSValue();
			createCookie("event_category", val);
			$(".eventCategory:first").val(val).trigger("select");
		});
	}
}

/************** POLL FUNCTIONS ******************/

loadPoll = function (pollCollID) {
	$("#pollBoxContent").fadeOut();
	$("#pollBoxOverlay").fadeIn("fast", function () {
		if (pollCollID != null && !isNaN(parseInt(pollCollID))) {
			$("#pollBoxContent").load("/ajaxcontent/BlogPoll.aspx?collid=" + pollCollID + "&pollIdx=" + curPollIdx + " #polls > *", function () {
				// Wire up button click events
				$("#btnSubmitPoll").click(function () {
					if ($(".pollQuestions:first input:checked").length > 0) {
						var pollID = $(".pollQuestions:first input:hidden:first").val();
						submitPoll(pollID);
					}
				});
				// Fade transparent overlay
				$("#pollBoxOverlay").fadeOut("fast");
				$("#pollBoxContent").fadeIn();
			});
		}
		else {
			$("#pollBox").fadeOut("fast");
		}
	});
}

nextPoll = function () {
	curPollIdx = parseInt($("#pollBoxContent input:hidden:last").val());
	loadPoll();
}

submitPoll = function (pollID) {
	var checkedControls = $(".pollQuestions:first input:checked");
	if (checkedControls.length > 0) {
		// Fade in overlay
		$(".pollQuestions:first").fadeOut(function () {
			$("#pollBoxOverlay").fadeIn(function () {
				$.ajax({
					type: "GET",
					url: "/handlers/SubmitPoll.ashx",
					data: {
						pollID: pollID,
						choice: $(checkedControls[0]).val(),
						oneTime: "false"
					},
					dataType: "html",
					cache: false,
					beforeSend: function () {
						// Disable the submit button
						$("#btnSubmit").attr("disabled", "true");
					},
					success: function (html) {
						loadPollResults(pollID);
					},
					error: function (xhr) {
						$("#pollBoxContent").html("<h4>We're sorry.  An error has occurred with our polling system.  Please check back later.</h4>");
						$("#pollBoxOverlay").fadeOut("fast");
					}
				});
			});
		});
	}
}

loadPollResults = function (pollID, cb) {
	var nextPollIdx = $("#pollBoxContent input:hidden:last").val();
	var showNextLink = (parseInt(nextPollIdx) == curPollIdx ? "0" : "1");
	$.ajax({
		url: "/ajaxcontent/PollResults.aspx",
		data: {
			id: pollID,
			showNextLink: showNextLink
		},
		dataType: "html",
		type: "GET",
		success: function (data, status, xhr) {
			$("#pollBoxContent").empty().append($("#pollResults", $.trim(data)));
			$(".pollResultValue").hide();
			$("#pollBoxOverlay").fadeOut("fast", function () {
				$(".pollResultRow").each(function () {
					// Extract the width value to use in animation
					var pct = $(".pollAnswerPct:first", this);
					if (pct != null) {
						// pct is a string containing a floating-point number (2 dec places) and a % sign at the end.
						// Truncate everything after the decimal point to get an integer.
						var wholePct = pct.html().split(".")[0];
						if (parseInt(wholePct) == 0) {
							$(".pollResultValue", this).hide();
						}
						else {
							$(".pollResultValue", this).animate({ width: wholePct + "%" }, 1500, "swing");
						}
					}
				});
			});
			$("#pollBoxContent").append("<input type=\"hidden\" value=\"" + nextPollIdx + "\" />");

			if (cb != null) { cb(); }
		}
	});

	//    $("#pollBoxContent").load("/ajaxcontent/PollResults.aspx?id=" + pollID + "&showNextLink=" + showNextLink + " #pollResults", function () {
	//        $(".pollResultValue").hide();
	//        $("#pollBoxOverlay").fadeOut("fast", function () {
	//            $(".pollResultRow").each(function () {
	//                // Extract the width value to use in animation
	//                var pct = $(".pollAnswerPct:first", this);
	//                if (pct != null) {
	//                    // pct is a string containing a floating-point number (2 dec places) and a % sign at the end.
	//                    // Truncate everything after the decimal point to get an integer.
	//                    var wholePct = pct.html().split(".")[0];
	//                    if (parseInt(wholePct) == 0) {
	//                        $(".pollResultValue", this).hide();
	//                    }
	//                    else {
	//                        $(".pollResultValue", this).animate({ width: wholePct + "%" }, 1500, "swing");
	//                    }
	//                }
	//            });
	//        });
	//        $("#pollBoxContent").append("<input type=\"hidden\" value=\"" + nextPollIdx + "\" />");

	//        if (cb != null) { cb(); }
	//    });
}

/************** SEARCH FUNCTIONS *******************/

$(document).ready(function () {
	$("#siteContent").show();
	// Set up search box
	var searchBox = $(".txtSearch:first");
	if (searchBox.val() == "" || searchBox.val() == "Search") {
		searchBox.addClass("noFocus").val("Search");
	}

	searchBox.focus(function () {
		var tb = $(this);
		if (tb.val() == "Search" && tb.hasClass("noFocus")) {
			tb.val("").removeClass("noFocus");
		}
	}).blur(function () {
		var tb = $(this);
		if (tb.val().trim() == "") {
			tb.val("Search").addClass("noFocus");
		}
	});
	$("#footerContainer a:last").css("border-right", "none");
});

checkSearch = function () {
	var tb = $(".txtSearch:first");
	return (tb.val() != "Search" && !tb.hasClass("noFocus"));
}

/************** TWITTER FUNCTIONS *******************/

var defaultQuery = "from=pbconnect";

getLatestTweet = function () {
	var q = defaultQuery;
	if ($("#footerTwitterBalloon input:hidden:first")[0]) {
		q = $("#footerTwitterBalloon input:hidden:first").val();
	}
	var url = "http://search.twitter.com/search.json?" + q + "&rpp=1&page=1&callback=?";
	$.getJSON(url, function (data) {
		if (data.results.length > 0) {
			var tweet = data.results[0];
			$("#footerTwitterBody").hide().empty().append($("<p>").html(twitterLinkURLReplace(tweet.text))).fadeIn();
			$("#footerTwitterDate").hide().empty().append($("<p>").html(formatTwitterDateTime(tweet.created_at).toString())).fadeIn();
		}
		else {
			$("#footerTwitterCntnr").hide(); // This should never happen...
		}
	});
}

getTwitterBoxLatestTweets = function (numTweets) {
	var q = defaultQuery;
	if ($("#footerTwitterBalloon input:hidden:first")[0]) {
		q = $("#footerTwitterBalloon input:hidden:first").val();
	}
	var url = "http://search.twitter.com/search.json?" + q + "&rpp=" + numTweets + "&page=1&callback=?";
	var twitterBoxCntnr = $(".twitterBoxTweetCntnr:first");
	$.getJSON(url, function (data) {
		$.each(data.results, function (i, tweet) {
			var tweetCntnr = $("<div class='tweetCntnr'>");
			$("<div class='tweet'>").append($("<p>").html(twitterLinkURLReplace(tweet.text))).appendTo(tweetCntnr);
			$("<div class='tweetDate'>").append($("<p>").html(formatTwitterDateTime(tweet.created_at).toString())).appendTo(tweetCntnr);
			tweetCntnr.hide().appendTo(twitterBoxCntnr).fadeIn();
		});
	});
}

formatTwitterDateTime = function (date) {
	var d = new Date(date);
	var today = new Date();

	// Compare dates.  If the tweet was from today, the string should read "Updated at xx:xx a/pm".  Otherwise, the string should read "Updated on mm/dd/yyyy at xx:xx a/pm".
	var ret = "Updated ";

	if (Math.round((today - d) / (1000 * 60 * 60 * 24)) > 0) { // Calculate the difference between d and today in days
		var month = d.getMonth() + 1;
		var day = d.getDate();
		var year = d.getFullYear();
		ret += " on " + month.toString() + "/" + day.toString() + "/" + year.toString();
	}
	
	var am = true;
	var h = d.getHours();
	if (d.getHours() > 12) {
		h = d.getHours() - 12;
		am = false;
	}
	var m = (d.getMinutes() < 10 ? "0" : "") + d.getMinutes();
	ret += " at " + h.toString() + ":" + m.toString() + " " + (am ? "AM" : "PM");
	return ret;
}

twitterLinkURLReplace = function (str) {
	str = str.replace(/(http\:.*?)(\s|$)/, "<a href='$1'>$1</a> ").replace(/\@(.*?)(\s|$)/g, " <strong>@<a class='twitterUserLink' href='http://twitter.com/$1'>$1</a></strong> ").replace(/\b(RT)\b/g, "<strong>$1</strong>");
	return str;
}

/************** COOKIE FUNCTIONS **********************/
function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

/******************* DART FUNCTIONS ***********************/

dart_click = function (dartCat, url, newPage) {
	var axel = Math.random() + "";
	var num = axel * 10000000000000;
	var spotpix = new Image();
	spotpix.src = "http://ad.doubleclick.net/activity;src=2709522;type=landi462;cat=" + dartCat + ";ord=" + num + "?";
	if (newPage) {
		window.open(url);
	}
	else {
		location.href = url;
	}
	return false;
}
function IsValidEmail(str) {
  if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(str)) {
   return (true);
  }
  return (false);
}
