var IE = 0//@cc_on+1
var howManyResults = new Array();

$(document).ready(function()
{
	// ***************************
	// NAV/HEADER
	// ***************************
	$("a#logo").click(function(){ window.open('http://libertymutual.com/'); return false; })
	
	// ***************************
	// SEARCH RESULTS
	// ***************************
	$('#search_bar #sub_nav a').click(function(){
		$('#search_bar #sub_nav a').removeClass('active');
		$('#results .result').hide();
		if(this.className!='')
			$('#results .'+this.className).show();
		else
			$('#results .result').show();
		$(this).addClass('active');
		return false;
	});
	
	
	
	if ($('.search').length > 0) {
		// hide the tabs with no results
		howManyResults["Film"] = 0;
		howManyResults["LG Polls"] = 0;
		howManyResults["Story"] = 0;
		howManyResults["Blog"] = 0;
		howManyResults["Page"] = 0;
	
		$('.search #results .result').each(function(i) {
			for (var key in howManyResults) {
				var localKey = key.replace(" ", "_");
				if (this.className.indexOf(localKey) > 0) {
					howManyResults[key] += 1;
					break;
				}
			}
		});
	
		for (var key in howManyResults) {
			if (howManyResults[key] == 0) {
				key = key.replace(" ", "_");
				$("#search #search_container #search_bar .subnav ." + key).hide();
			}
		}
	}	
	// *********************************************************************************************************
	// IF YOU'RE IN THE HOME OR FILMS PAGE
	// *********************************************************************************************************

	if($('#home_film').length > 0 || $('body.films').length > 0)
	{
		// FOR THE FIRST FILM
		var firstElemInList = $('#topics dl:first')[0];
		if (firstElemInList.className.indexOf('film')  > 0) {
			$('#home_film #intro h3').html($('#topics dl:first dt').html());
			$('#home_film #intro h4').html($('#topics dl:first .director').html());
			$('#home_film #intro p.runtime').html($('#topics dl:first .duration').html());
			if ($('#home_film #home_film_link')[0])
				$('#home_film #home_film_link')[0].href = $('#topics dl:first dt a')[0].href;
			
			
			if($('#home_film #intro .button a')[0])
				$('#home_film #intro .button a')[0].href = $('#topics dl:first dt a')[0].href;

			if($('#topics dl:first .preview img').length > 0)
				$('#home_film #home_film_link > img')[0].src = $('#topics dl:first .preview img')[0].src;
		} else {
			$('#home_film').css({'display' : 'none'});
			$('#home_story').css({'display' : 'none'});
			$('#home_intro').css({'display' : 'block'});
			img_tag = $(firstElemInList).find('.image img');
			span_tag = $(firstElemInList).find('.image span');
			span_html = span_tag[0] ? span_tag[0].innerHTML : '';
			$('#home_intro span a')[0].innerHTML = img_tag.length > 0 ? "<img src='"+img_tag[0].src+"' />" : "<img src='"+span_html+"' />";
			$('#home_intro h3').html($(firstElemInList).find('dt').html());
			$('#home_intro h4').html($(firstElemInList).find('.director').html() + ' ' + $(firstElemInList).find('.comments').html());
			$('#home_intro p:first').html($(firstElemInList).find('.excerpt').html());
			$('#home_intro p:last a')[0].href = $('#home_intro h3 a')[0].href;
		}
		
		// IF THE POPULAR BUTTON IS CLICKED SHOW POPULAR POSTS, RE-INIT SCROLLBAR
		$('a.button.popular').click(function(){
			$('#topic_scroll dl').hide();
			$('#topic_scroll dl.popular').show();
			if(!IE){ $('#topics').jScrollPane({scrollbarWidth:16, showArrows:true}); }
			$('#sort_by a').removeClass('button_active');
			$(this).addClass('button_active');
		});
	
		// IF THE RECENT BUTTON IS CLICKED SHOW RECENT POSTS, RE-INIT SCROLLBAR
		$('a.button.recent').click(function(){
			$('#topic_scroll dl').show();
			$('#topic_scroll dl.popular').hide();
			if(!IE){ $('#topics').jScrollPane({scrollbarWidth:16, showArrows:true}); }
			$('#sort_by a').removeClass('button_active');
			$(this).addClass('button_active');
		});
		
		// HIDE ALL BLOG ITEMS IF THERE ARE NO THUMBNAILS
		$('dl.blog .thumb').each(function(){
		    if(jQuery.trim($(this).html()) == '')
		    {
		        $(this).parent().hide();    
		    }
		});
		// FOR HOVERS OVER THE LIST ON THE RIGHT
		$('#topics dl').hover(
		  function ()
		  {
		  	if($('body.films').length==0)
			{
			  	if(this.className.indexOf('film') > 0)
				{
					$('#home_intro').hide();
					$('#home_story').hide();
					$('#home_film').show();
					if($('#home_film #intro').length > 0)
					{
						$('#home_film #intro h3').html($(this).find('dt').html());
						$('#home_film #intro h4').html($(this).find('.director').html());
						$('#home_film #intro p.runtime').html($(this).find('.duration').html());
						$('#home_film #intro .button a')[0].href = $(this).find('dt a')[0].href;
						img_tag = $(this).find('.preview img');
						span_tag = $(this).find('.preview span');
						$('#home_film #home_film_link > img')[0].src = img_tag.length > 0 ? img_tag[0].src : span_tag[0].innerHTML;
						$('#home_film #home_film_link')[0].href = $(this).find('dt a')[0].href;
					}

				} else if(this.className.indexOf('blog') > 0){
					$('#home_film').hide();
					$('#home_story').hide();
					$('#home_intro').show();
					img_tag = $(this).find('.image img');
					span_tag = $(this).find('.image span');
					span_html = span_tag[0] ? span_tag[0].innerHTML : '';
					$('#home_intro span a')[0].innerHTML = img_tag.length > 0 ? "<img src='"+img_tag[0].src+"' />" : "<img src='"+span_html+"' />";
					$('#home_intro h3').html($(this).find('dt').html());
					$('#home_intro h4').html($(this).find('.director').html() + ' ' + $(this).find('.comments').html());
					$('#home_intro p:first').html($(this).find('.excerpt').html());
					$('#home_intro p:last a')[0].href = $('#home_intro h3 a')[0].href;

				} else if(this.className.indexOf('story') > 0){
					$('#home_film').hide();
					$('#home_intro').hide();
					$('#home_story').show();
					$('#home_story h3').html($(this).find('dt').html());
					$('#home_story p:first').html($(this).find('.excerpt').html());
					$('#home_story p:last a')[0].href = $('#home_intro h3 a')[0].href;
				}	
			}
		    $(this).addClass('over');
		  },
		  function () {
		    $(this).removeClass('over');
		  }
		);
		// ***************************
		// Topic selector formatting and event handling
		// ***************************
		
		// build the topic/category list
		var unq = '';
		var unq_arr = new Array();
		$('dd.categories a').each(function(){
			if(this.className!='')
			{
					if(unq.indexOf(this.className) < 0){
						unq = unq + ' ' + this.className;
					}
			}
			unq = $.trim(unq);
			unq_arr = unq.split(' ');
		});
		$('#topic_select ul').append("<li><a href=\"/blog/categories/\">All Topics</a></li>");
		for(i=0;i<unq_arr.length;i++)
		{
			$('#topic_select ul').append("<li><a href=\"/blog/categories/"+unq_arr[i].toLowerCase()+"/\">"+unq_arr[i]+"</a></li>");
		}
		if(unq_arr.length % 2 == 0){ $('#topic_select ul').append("<li><a href=\"#\" disabled=\"true\" style=\"text-decoration:none\">&nbsp;</a></li>"); }
		
		$('#topic_select li:odd').css({width:'149px'});
		$('#topic_select li a:odd').css({border:'none', borderLeft:'solid 1px #D9D9D9'});
		home_topics = $('#topic_select li').length;
		if(home_topics > 0)
		{
			$('#topic_select li:nth-child('+(home_topics-1)+') a').css({background:'none'});
			$('#topic_select li:last a').css({background:'none'});
		}
		
		// if it's clicked, hide everything in the slider but its selected category name
		$('#topic_select li a').click(function(){
			$('#topic_select').hide();
			$('#topics dl').hide();
			if(this.innerHTML == 'All Topics')
			{
				$('#topics dl.regular').fadeIn("slow");
			} else {
				$('dl.regular dd.categories a.'+this.innerHTML).parent().parent().fadeIn("slow");
			}
			
			// re-init the scrollbar
			if(!IE){ $('#topics').jScrollPane({scrollbarWidth:16, showArrows:true}); }
			return false;
			
		});
		// ***************************
		
		if(!IE)
		{ 
			$('#topics').jScrollPane({scrollbarWidth:16, showArrows:true}); 
			$('#topics').css({overflow:'visible'});
			
		}
		$('.jScrollPaneContainer').css({width:342});
	}
	
	$('a.selector_header').click(function(){
		$('#topic_select').toggle();
		return false;
	});
	
	$('a[disabled="true"]').click(function(){ return false; });
	
	// ***************************
	// TODO: DRY up the following.
	// ***************************
	
	$('.with_posts .content #sidebar #topics li:odd').css({width:'131px'});
	$('.with_posts .content #sidebar #topics li a:odd').css({border:'none', borderLeft:'solid 1px #D9D9D9'});
	total_topics = $('.with_posts .content #sidebar #topics li').length
	if(total_topics > 0)
	{
		$('.with_posts .content #sidebar #topics li:nth-child('+(total_topics-1)+') a').css({background:'none'});
		$('.with_posts .content #sidebar #topics li:last a').css({background:'none'});
	}
	if($('.with_posts .content #posts .post').length > 1){ $('.with_posts .content #posts .post:first').css({paddingTop:'10px'}); }
	$('.with_posts .content #posts .post:first').css({borderTop:'none'});

	// 

	if($('body.films #flashContent').length > 0)
	{
		swfobject.embedSWF("http://preview.devkit.permissiontv.com/Preloader.swf", "flashContent", "606", "342", "9.0.0", "/Flash/expressinstall.swf", flashvars, params);
	}
	
	
	if ($('#POVEntryFlash').length > 0) {
		//swfobject.embedSWF("/Flash/pollSecond.swf", "povPoll", "562", "204", "9.0.0", "/Flash/expressinstall.swf", {"pollId": pollid}, {"bgcolor": "#ffffff", "allowFullScreen": "false", "allowScriptAccess": "sameDomain", "wmode":"transparent"});
	}
	
	$("#whatWeDoTabs li").bind("click", function(e) 
	{
	    var clicked = e.target;
	    if ($(clicked).hasClass("active")) return;
	    else {
	        $("#whatWeDoTabs li").each(function(i) {
	            $(this).removeClass("active");
	        });
	        $("#whatWeDoContent div").each(function(i) {
	            $(this).removeClass("active");
	        });
	        $(clicked).toggleClass("active");
	        var idx = 0;
	        for (var i=0; i<$("#whatWeDoTabs li").length; i++) {
	            var elt = $("#whatWeDoTabs li")[i];
	            if (elt == clicked) {
                    idx = i; 
                    break;
                }
	        }
	        $("#whatWeDoContent div").each(function(i) {
	            if (i == idx) $(this).toggleClass("active");
	        });
	        
	    }
	});
	
	// Add in the name and email to the comment field since we don't have those as fields in EE
	$("form#entryform button").bind("click", function(e) {
        document.getElementById('field_id_75').value += "\n\n Name: " + document.getElementById('yourname').value + " \n\n Email: " + document.getElementById('youremail').value;
	});
	
	// Poll SWFObject embedding
	if ($('#homePoll').length > 0) {
        swfobject.embedSWF("/Flash/pollFront.swf", "homePoll", "290", "62", "9.0.0", "/Flash/expressinstall.swf", {"pollId": pollid}, {"bgcolor": "#ffffff", "allowFullScreen": "false", "allowScriptAccess": "sameDomain", "wmode":"transparent"});
    }
    if ($('#povPoll').length > 0) {
        swfobject.embedSWF("/Flash/pollSecond.swf", "povPoll", "562", "204", "9.0.0", "/Flash/expressinstall.swf", {"pollId": pollid}, {"bgcolor": "#ffffff", "allowFullScreen": "false", "allowScriptAccess": "sameDomain", "wmode":"transparent"});
    }
	
	// Set the correct tab in the film_details section
	if($('#film_details').length > 0)
	{
		swap_film_tabs('#film_contributors');
		swap_film_tabs('#film_comments');
		swap_film_tabs('#film_synopsis');
		$('#film_details .post:last').css({border:'none'});
	}
	
	
	// Comment field validation for all the places you can comment
	// TODO: DRY this up
	$("form#comment_form input.submit, form#contact_form input.submit").bind("click", function(){
		var ret = true;
		var elt = $("form#comment_form").length>0?"form#comment_form":"form#contact_form";
		
		if ($(elt + " input[name='name']").length > 0 && jQuery.trim($(elt + " input[name='name']").val()) == '') {
			$(elt + " input[name='name']").css({border:'1px solid red'});
			if ($("#requiredname").length == 0)
				$(elt + " input[name='name']").after("<span class='requiredmessage' id='requiredname'>* Required</span>");
			else $("#requiredname").show();
			$(elt + " input[name='name']").bind("click", function(e) {
				$("#requiredname").hide();
				$(elt + " input[name='name']").css({border:'1px solid #b2b2b2'});
			});
			ret = false;
		} 
		if ($(elt + " input[name='email']").length > 0 && jQuery.trim($(elt + " input[name='email']").val()) == '') {
			$(elt + " input[name='email']").css({border:'1px solid red'});
			if ($("#requiredemail").length == 0)
				$(elt + " input[name='email']").after("<span class='requiredmessage' id='requiredemail'>* Required</span>");
			else $("#requiredemail").show();
			$(elt + " input[name='email']").bind("click", function(e) {
				$("#requiredemail").hide();
				$(elt + " input[name='email']").css({border:'1px solid #b2b2b2'});
			});
			ret = false;
		} 
		if (elt != "form#comment_form") {
			if ($(elt + " input[name='location']").length > 0 && jQuery.trim($(elt + " input[name='location']").val()) == '') {
				$(elt + " input[name='location']").css({border:'1px solid red'});
				if ($("#requiredlocation").length == 0)
					$(elt + " input[name='location']").after("<span class='requiredmessage' id='requiredlocation'>* Required</span>");
				$("#requiredlocation").show();
				$(elt + " input[name='location']").bind("click", function(e) {
					$("#requiredlocation").hide();
					$(elt + " input[name='location']").css({border:'1px solid #b2b2b2'});
				});
				ret = false;
			}
		}
		if ($(elt + " textarea[name='comment']").length > 0 && jQuery.trim($(elt + " textarea[name='comment']").val()) == '') {
			$(elt + " textarea[name='comment']").css({border:'1px solid red'});
			if ($("#requiredcomment").length == 0)
				$(elt + " textarea[name='comment']").after("<span class='requiredmessage' id='requiredcomment'>* Required</span>");
			else $("#requiredcomment").show();
			$(elt + " textarea[name='comment']").bind("click", function(e) {
				$("#requiredcomment").hide();
				$(elt + " textarea[name='comment']").css({border:'1px solid #b2b2b2'});
			});
			ret = false;
		}
		if ($(elt + " input[name='from']").length > 0 && jQuery.trim($(elt + " input[name='from']").val()) == '') {
			$(elt + " input[name='from']").css({border:'1px solid red'});
			if ($("#requiredfrom").length == 0)
				$(elt + " input[name='from']").after("<span class='requiredmessage' id='requiredfrom'>* Required</span>");
			else $("#requiredfrom").show();
			$(elt + " input[name='from']").bind("click", function(e) {
				$("#requiredfrom").hide();
				$(elt + " input[name='from']").css({border:'1px solid #b2b2b2'});
			});
			ret = false;
		}
		if ($(elt + " input[name='to']").length > 0 && jQuery.trim($(elt + " input[name='to']").val()) == '') {
			$(elt + " input[name='to']").css({border:'1px solid red'});
			if ($("#requiredto").length == 0) 
				$(elt + " input[name='to']").after("<span class='requiredmessage' id='requiredto'>* Required</span>");
			else $("#requiredto").show();
			$(elt + " input[name='to']").bind("click", function(e) {
				$("#requiredto").hide();
				$(elt + " input[name='to']").css({border:'1px solid #b2b2b2'});
			});
			ret = false;
		}
		if ($("#share-note").length == 0) {
			if ($(elt + " textarea[name='message[]']").length > 0 && jQuery.trim($(elt + " textarea[name='message[]']").val()) == '') {
				$(elt + " textarea[name='message[]']").css({border:'1px solid red'});
				if ($("#requiredmessage").length == 0)
					$(elt + " textarea[name='message[]']").after("<span class='requiredmessage' id='requiredmessage'>* Required</span>");
				else $("requiredmessage").show();
				$(elt + " textarea[name='message[]']").bind("click", function(e) {
					$("#requiredmessage").hide();
					$(elt + " textarea[name='message[]']").css({border:'1px solid #b2b2b2'});
				});
				ret = false;
			}
		}
		if ($(elt + " input[name='message[]'][type!='hidden'][class!='go']").length > 0 && jQuery.trim($(elt + " input[name='message[]'][type!='hidden'][class!='go']").val()) == '') {
			$(elt + " input[name='message[]'][type!='hidden'][class!='go']").css({border:'1px solid red'});
			if ($("#requiredmessage2").length == 0)
				$(elt + " input[name='message[]'][type!='hidden'][class!='go']").after("<span class='requiredmessage' id='requiredmessage2'>* Required</span>");
			else $("#requiredmessage2").show();
			$(elt + " input[name='message[]'][type!='hidden'][class!='go']").bind("click", function(e) {
				$("#requiredmessage2").hide();
				$(elt + " input[name='message[]'][type!='hidden'][class!='go']").css({border:'1px solid #b2b2b2'});
			});
			ret = false;
		}
		if (ret == true) {
			$(elt + "form")[0].submit();
			return ret;
		} else {
			return ret;
		}
	});
	
	// Homepage video embedding
	if ($("#introVideoContainer").length > 0) {
		if (getCookieRPDOTCOM("responsibilityProjectIntroVideoPlayed") != "true") {
			$("#introVideoContainer").show();
			$("#introVideoSkipIntro").show();
		} else {
			$("#showcase .content").css({visibility:"visible"});
		}
	
		var flashvarsHomePage = new Object();
		flashvarsHomePage.applicationSwf = "http://preview.channels.permissiontv.com/c1043322/staging/packages/PDP/files/qs_help_bandwidth.swf";
		flashvarsHomePage.licenseKey = "06e2dd49-92cf-46d7-8ecc-cc5f7bcf2eea";
		flashvarsHomePage.channelID = "1043322";
		flashvarsHomePage.environment = "preview";
		flashvarsHomePage.login = "http://services.permissiontv.com/v2.2/auth/login.xml";
		flashvarsHomePage.services = "http://services.permissiontv.com/v2.2/services.xml";
		flashvarsHomePage.PID = "1090291";
		flashvarsHomePage.CID = "1095541";
		var paramsHomePage = new Object();
		paramsHomePage.allowFullScreen = "true";
		paramsHomePage.AllowScriptAccess = "always";
		paramsHomePage.wmode = "opaque";
		var ptvAttributes = new Object();
		ptvAttributes.id = "ptvPlayer";
		ptvAttributes.name = "ptvPlayer";
		swfobject.embedSWF("http://preview.devkit.permissiontv.com/Preloader.swf", "introVideo", "955", "377", "9.0.0", "/Flash/expressinstall.swf", flashvarsHomePage, paramsHomePage, ptvAttributes);
	
	
		$("#introVideoSkipIntro").bind("click", function(e) {
			document.getElementById('ptvPlayer').stopVideo();
			$("#showcase .content").css({visibility:"visible"});
			$("#introVideoContainer").hide();
			$("#introVideoSkipIntro").hide();
			setCookieRPDOTCOM("responsibilityProjectIntroVideoPlayed", "true", 365);
			s.tl(this, 'o', 'Skip Intro');
		});
	
		$("#sort_by span").bind("click", function(e){
			$("#showcase .content").css({visibility:"hidden"});
			$("#introVideoContainer").show();
			$("#introVideoSkipIntro").show();
			document.getElementById('ptvPlayer').playVideo();
			s.tl(this, 'o', 'Replay Intro');
		});
	}
	
	$("#selectedTopic").bind("click", function(e) {
		$('#topic_select').toggle();
		return false;
	});
	
	$("#topic_select li a").bind("click", function(e) {
		$("#selectedTopic").text(e.target.innerHTML);
		$("#topics dl:first").mouseover()
	});
	
	// Newsletter Event Binding
	$("#newsletterModal").bind("click", function(e) {
		$.floatbox({
			ajax: {
				url: "/contact/newsletter_modal/"
			},
			bgConfig: {
				position: (IE)?"absolute":"fixed",
				zIndex: "1000",
				width: "100%",
				height: "100%",
				top: 0,
				left: 0,
				backgroundColor: "#000000",
				opacity: 0.75
			},
			boxConfig: {
				backgroundColor:"transparent",
				zIndex:"1001",
				position:"absolute",
				top:variablePopupY(e),
				left:variablePopupX(e)
			},
			fade: true
		});
	});
	
});

/*
 * Start Newsletter Popup JS
 */

function closeModalDialogue() {
	$("#newsletterForm").html("<h2>Thank you for signing up for our newsletter!</h2>");
	setTimeout(doCloseDialogue, 2000);
}

function doCloseDialogue() {
	$(".close-floatbox:first").trigger("click");
}

function validateAJAXForm() {
	if (jQuery.trim($("#contact-name").val()) == "" || jQuery.trim($("#contact-email").val()) == "" ) {
		return false;
	}
}

function submitNewsletterRequest(theForm) {
	$.ajax( {
		type: "POST",
		url: "/",
		data: $(theForm).serialize(),
		beforeSend: validateAJAXForm,
		success: closeModalDialogue
	});
	return false;
}

function variablePopupX(evt) {
	var offset = $(evt.target).offset();
	return offset.left-20;
}

function variablePopupY(evt) {
	var offset = $(evt.target).offset();
	return offset.top-300;
}

/*
 * End Newsletter Popup JS
 */

function onVideoComplete() {
	$("#showcase .content").css({visibility:"visible"});
	$("#introVideoContainer").hide();
	$("#introVideoSkipIntro").hide();
	setCookieRPDOTCOM("responsibilityProjectIntroVideoPlayed", "true", 365);
}

function swap_film_tabs(divid)
{
	$('a[href="'+divid+'"]').click(function(){
		$('#film_details .title_bar a').removeClass('active');
		$(this).addClass('active');
		$('#film_details div.content').hide();
		$(divid).show();
		return false;
	});
}

/*
 * JS Cookie Functions from http://www.w3schools.com/JS/js_cookies.asp
 */

function setCookieRPDOTCOM(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookieRPDOTCOM(c_name) {
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
	    { 
	    c_start=c_start + c_name.length+1; 
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    return unescape(document.cookie.substring(c_start,c_end));
	    } 
	  }
	return "";
}
