////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DOCUMENT READY
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$(document).ready(function(){
	
	//Home
	isHome = $("body").hasClass('homePage');
	if (isHome) { sliderInit(); textScrollerInt(); }
	
	//Network products
	isNetwork = $("body").hasClass('networkProductsPage');
	if (isNetwork) {networkProductsInt() }
	
	//Get a quote
	isQuote = $("body").hasClass('quotePage');
	if (isQuote) { getQuoteInt() }
	
	//Stats
	isStats = $("body").hasClass('userStatsPage');
	if (isStats) { whereStatsInit() }
	 
	//Map
	isMap = $("body").hasClass('mapPage');
	if (isMap) { intInteractiveMap() }
	  
    //Who are they
	isUsers = $("body").hasClass('usersPage');
	if (isUsers) {	whoAreThey() }
	
	 //Brand Awareness
	isUsers = $("body").hasClass('brandAwarenessPage');
	if (isUsers) {	subNavInt() }
	
	//WorkShop
	isWorkshop = $("body").hasClass("workshop-js");
	if (isWorkshop) { workshop() }
});

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//BRAND AWARENESS SUB NAV INT
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function subNavInt(){
	
	var brandDivs = $("div.contentSwitch");
	
	brandDivs.hide();
	brandDivs.eq(0).show();
	
	$("#contentNav li").each(function(i, obj){
		$(obj).data('id', i);
	});
	
	$("#contentNav li a").click(function(){
		$(this).parent().parent().parent().find("ul li.active").removeClass("active");										   
		$(this).parent().addClass("active");
		
		i = $(this).parent().data('id');
		
		brandDivs.hide();
		brandDivs.eq(i).show();
		
    });
	
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Slider Call backs	- HOME PAGE
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function slider_initCallback(carousel) {
	$('.slider-control a').bind('click', function() {
		carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
		if($("ul.pause li").hasClass("active")) {
			$("ul.pause li").removeClass("active");
		}
		return false;
	});

	$('#slider-next').bind('click', function() {
		carousel.next();
		if($("ul.pause li").hasClass("active")) {
			$("ul.pause li").removeClass("active");
		}
		return false;
	});

	$('#slider-prev').bind('click', function() {
		carousel.prev();
		if($("ul.pause li").hasClass("active")) {
			$("ul.pause li").removeClass("active");
		}
		return false;
	});
	
	// Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Restart animation if paused when you click the slide.
/*    $("#slider ul").mousedown(function() {
        carousel.next();
		if($("ul.pause li").hasClass("active")) {
			$("ul.pause li").removeClass("active");
		}
    });*/
	
	//Pause function
	$("ul.pause li a.pause").click(function(){
		if($(this).parent().hasClass("active")) {
			$(this).parent().removeClass("active");
			carousel.next(); //Play
			return false;
		} else {
			$(this).parent().addClass("active");	
			carousel.stopAuto(); //Pause
		}
	});

	
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Slider Call Backs
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//var carouselFlash = true;

/**
 * This is the callback function which receives notification  when an item becomes the first one in the visible range. Triggered after animation. */
function mycarousel_itemVisibleInCallbackAfterAnimation(carousel, item, idx, state) {
	$("ul.slider-control li.active").removeClass("active");
	$("ul.slider-control li").eq(idx - 1).addClass("active");
	//if(idx != 1 && idx != 2 && carouselFlash) {		
		//resetSwf("movie-" + idx);	
	//if (homepageFlash != undefined)
		//homepageFlash("play", "movie-" + idx);
	//} 
};

/**
 * This is the callback function which receives notification when an item becomes the first one in the visible range. Triggered before animation. */
/*function mycarousel_itemVisibleInCallbackBeforeAnimation(carousel, item, idx, state) {
	if(idx != 1) {
		//resetSwf("movie-" + idx);
		homepageFlash("reset", "movie-" + idx);
	}
};*/

/**
 * This is the callback function which receives notification when an item is no longer the first one in the visible range. */
function mycarousel_itemFirstOutCallback(carousel, item, idx, state) {
	/*if(idx != 1 && idx != 2 && carouselFlash) {	
		//resetSwf("movie-" + idx);
		if (homepageFlash != undefined)
			homepageFlash("reset", "movie-" + idx);
	}*/
};



////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//HOME PAGE Int
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function sliderInit() {
	//Init Slider					   
	$("#Slider").jcarousel({
		scroll: 1,
		auto: 13,
		wrap: 'last',
		initCallback: slider_initCallback,
		itemFirstOutCallback: mycarousel_itemFirstOutCallback,
		itemVisibleInCallback: {
			//onBeforeAnimation: mycarousel_itemVisibleInCallbackBeforeAnimation,
			onAfterAnimation:  mycarousel_itemVisibleInCallbackAfterAnimation
		 },
		// This tells jCarousel NOT to autobuild prev/next buttons
		buttonNextHTML: null,
		buttonPrevHTML: null
	});
	
	//Home Page slider active button
	$("ul.slider-control li a").click(function(){
		
		if ($(this).parent().hasClass("active")) {
			//Leave as is	
		} else {
			$("ul.slider-control li").removeClass("active");
			$(this).parent().addClass("active");
		}
	});
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//NETWORK PRODUCTS Int
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function networkProductsInt() {
	
	networkProducts();
	
	function sliderActive(a){
		//Handle active link states
		if (a.parent().hasClass("active")) {				
		} else {
			$("#productsNav li").removeClass("active");
			a.parent().addClass("active");
		}
	}
	
	function networkFader(aRel){
		slide.fadeOut(0);
		slide.eq(aRel).fadeIn(0);
	}
	
	function timerStop(){
		jQuery.stopTimer();
	}
	
	function timerLoop(){
		jQuery.fjTimerEach({
		interval: 3000,
			repeat: true,
		tick: function(counter, object) {
			networkFader(object);
					a = $("#productsNav li a").eq(object);
					sliderActive(a);
		},
		array: [0, 1, 2],
		onComplete: timerLoop
		});
	}
	
	function networkProducts() {
		slide = $("#Products .networkSlider");
	
		slide.hide();
		slide.eq(0).show();
	
		timerLoop();
		
		$("#productsNav li a").click(function(){
			a = $(this);
			sliderActive(a);
	
			aRel = a.attr('rel');
			networkFader(aRel);	
	
			timerStop();
		});
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Get A Quote Int
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getQuoteInt() {
	
	var box = $("#subNav li input:checkbox");

	//Check if any are checked on page load	
	for(i=0; i < box.length; i++) {
		var a = box.eq(i);
		isChecked(a);	
	}
	
	//Run Check function when an input is clicked
	box.click(function(){
		var a = $(this);
		isChecked(a);		
	});
	
	//Function to add or remove checked class
	function isChecked(clickedBox) {
		if( clickedBox.is(":checked") ) {
			clickedBox.parent().addClass("selected");	
		} else {
			clickedBox.parent().removeClass("selected");	
		}
	}

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Form Validation - Submit a Testimonial
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function validateTestimonialForm() {

//$().ready(function() {	
	// validate signup form on keyup and submit
	$("#testimonialSubmissionDisplayForm").validate({
		rules: {
			'data[Testimonial][firstName]': "required",
			'data[Testimonial][surname]': "required",
			'data[Testimonial][businessName]': {
				required: true
			},
			phoneNumberOne: {
				minlength: 2,
				number: true
			},
			phoneNumberTwo: {
				minlength: 4,
				number: true
			},
			phoneNumberThree: {
				minlength: 4,
				number: true
			},
			mobileNumberOne: {
				minlength: 4,
				number: true
			},
			mobileNumberTwo: {
				minlength: 3,
				number: true
			},
			mobileNumberThree: {
				minlength: 3,
				number: true
			},		
			'data[Testimonial][suburb]': {
				required: true
			},
			'data[Testimonial][state]': {
				required: true,
				minlength: 1
			},
			'data[Testimonial][emailAddress]': {
				email: true
			},
			'data[Testimonial][postcode]': {
				required: true,
				minlength: 4,
				number: true
			}
		},
		groups: {
		        fullPhoneNumber: "phoneNumberOne phoneNumberTwo phoneNumberThree",
				fullMobileNumber: "mobileNumberOne mobileNumberTwo mobileNumberThree"
		    },
		messages: {
			'data[Testimonial][firstName]': "Please enter your first name",
			'data[Testimonial][surname]': "Please enter your last name",
			'data[Testimonial][businessName]': {
				required: "Please enter your business name"
			},
			'data[Testimonial][suburb]': "Please enter your business suburb",
			'data[Testimonial][state]': "Please enter your business state",
			'data[Testimonial][emailAddress]': "Please enter a valid email address",
			'data[Testimonial][postcode]': {
				required: "Please enter your business postcode",
				minlength: "Postcode must be 4 digits"
			},
			
			errorPlacement: function(error, element) {
			      if (element.attr("name") == "phoneNumberOne" || element.attr("name") == "phoneNumberTwo" || element.attr("name") == "phoneNumberThree") 
			      error.insertAfter("#phoneNumberThree");
			      else 
			      error.insertAfter(element);
			   }
		}	
	});
		jQuery.validator.addMethod('eitherPhone', function(val, el) {
	        var $module = $(el).parents('div.content');
	        return $module.find('.eitherPhone:filled').length;
	});
		jQuery.validator.addClassRules('eitherPhone', {
	        'eitherPhone' : true
	});
		jQuery.validator.messages.eitherPhone = 'Please provide at least one phone number';
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Form Validation - Quote Form
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function validateQuoteForm() {

//$().ready(function() {	
	// validate signup form on keyup and submit
	$("#ContactSubmitForm").validate({
		rules: {
			'data[Contact][businessName]': {
				required: true
			},
			'data[Contact][businessPhoneArea]': {
				minlength: 2,
				number: true,
				required: true
			},
			'data[Contact][businessPhoneMid]': {
				minlength: 4,
				number: true,
				required: true
			},
			'data[Contact][businessPhoneLast]': {
				minlength: 4,
				number: true,
				required: true
			},
			'data[Contact][businessMobileFirst]': {
				minlength: 4,
				number: true,
				required: true
			},
			'data[Contact][businessMobileMid]': {
				minlength: 3,
				number: true,
				required: true
			},
			'data[Contact][businessMobileLast]': {
				minlength: 3,
				number: true,
				required: true
			},		
			'data[Contact][firstName]': {
				required: true
			},
			'data[Contact][lastName]': {
				required: true,
				minlength: 1
			},
			'data[Contact][personalEmail]': {
				email: true
			},
			'data[Contact][personalEmailConfirm]': {
				email: true,
				equalTo: '#ContactPersonalEmail'
			},
			'data[Contact][phoneNumberArea]': {
				minlength: 2,
				number: true
			},
			'data[Contact][phoneNumberMid]': {
				minlength: 4,
				number: true
			},
			'data[Contact][phoneNumberLast]': {
				minlength: 4,
				number: true
			},
			'data[Contact][mobileNumberFirst]': {
				minlength: 4,
				number: true
			},
			'data[Contact][mobileNumberMid]': {
				minlength: 3,
				number: true
			},
			'data[Contact][mobileNumberLast]': {
				minlength: 3,
				number: true
			}
		},
		groups: {
		        fullPhoneNumber: "'data[Contact][phoneNumberArea]' 'data[Contact][phoneNumberMid]' 'data[Contact][phoneNumberLast]'",
				fullMobileNumber: "'data[Contact][mobileNumberFirst]' 'data[Contact][mobileNumberMid]' 'data[Contact][mobileNumberLast]'"
		    },
		messages: {
			'data[Contact][businessName]': "Please enter your business name",
			'data[Contact][businessPhoneArea]': "Please enter your business area code",
			'data[Contact][businessPhoneMid]': "Please enter a complete phone number",
			'data[Contact][businessPhoneLast]': "Please enter a complete phone number",
			'data[Contact][businessMobileFirst]': "Please enter a complete mobile number",
			'data[Contact][businessMobileMid]': "Please enter a complete mobile number",
			'data[Contact][businessMobileLast]': "Please enter a complete mobile number",
			'data[Contact][firstName]': "Please enter your first name",
			'data[Contact][lastName]': "Please enter your last name",
			'data[Contact][personalEmail]': "Please enter a valid email address",
			'data[Contact][personalEmailConfirm]': {
				email: "Please enter a valid email address",
				equalTo: "Email addresses must match"
			},
			
			errorPlacement: function(error, element) {
			      if (element.attr("name") == "'data[Contact][businessPhoneArea]'" || element.attr("name") == "'data[Contact][businessPhoneMid]'" || element.attr("name") == "'data[Contact][businessPhoneLast]'") 
			      error.insertAfter("'data[Contact][businessPhoneLast]'");
			      else 
				  error.insertAfter(element);
			}
		}	
});
		jQuery.validator.addMethod('eitherContactPhone', function(val, el) {
	        var $module = $(el).parents('div.content');
	        return $module.find('.eitherContactPhone:filled').length;
		});
		jQuery.validator.addClassRules('eitherContactPhone', {
	        'eitherContactPhone' : true
		});
		jQuery.validator.messages.eitherContactPhone = 'Please provide at least one phone number';
		//});
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//User Statistc Int
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function whereStatsInit(){

	$(".stats-box").each(function() {
		var toggleArea = $(this).find(".toggle");
		var statsBox = $(this);
		toggleArea.hide();
		
		var toggleButton = $(this).find("h3, a.expand");
		toggleButton.click(function() {
			if (toggleArea.is(":visible")) {
				toggleArea.slideUp("slow");
				toggleButton.removeClass("open");
				$(".toggle").find("sup").fadeOut(300);
			} else {
				toggleArea.slideDown("slow");
				toggleButton.addClass("open");
				$(".toggle").find("sup").show();
			}
			statsBox.toggleClass("open");
		});
	});
	
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Market Reach by Area - INTERACTIVE MAP
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function intInteractiveMap() {
	
//
//	Variables
//
	var selectionContainer = $(".selection");
	var selectionInput = $(".selection input");
	var mapBullet = $("#map-content a.bullet");
	var mapArea = $("#Map area");
	var tableRows = $("table.stats-table tr");
	var stateDiv = $(".state-hover");

//
//	Setup Page
//	
	stateDiv.hide();
	selectionContainer.hide();
	$("table.stats-table tr").hide();
	$("p.cluster").hide();
	$(".selection input").attr("checked", false);
	
//
//	Append reference Id's
//
	selectionContainer.each(function(i){
		$(this).attr("data-id", i);									 
	 });
	selectionInput.each(function(i){
		$(this).attr("data-id", i);									 
	 });
	mapBullet.each(function(i){
		$(this).attr("data-id", i);									 
	 });
	mapArea.each(function(i){
		$(this).attr("data-id", i);									 
	 });
	tableRows.each(function(i){
		$(this).attr("data-id", i);									 
	 });
	
//
//	Check if there are rows present after each update
//
	function tableRowCheck() {
		//If no rows present hide table
		if ($(".stats-table tr:visible").size() == 1) {
			$(".stats-table").hide();	
			$("p.cluster").hide();
		} 	
		//Check if disclaimer needs to be shown
		if ($(".stats-table tr[data-cluster=true]:visible")) {
		} else {
			$("p.cluster").hide();
		}
		
	}
	
//
//	Check if disclaimer needs to be shown
//
	function clusterCheck(val, related) {
		//Show cluster Items		
		if (val == "true") {
			
			codes = related.split("|");
			tableCodes = $("table.stats-table tr td:first").text();						
			
			for (i=0; i < codes.length; i++){
				if (tableCodes = codes[i]){
					$("table.stats-table tr td[data-code=" + codes[i] +"]").parent().show();
					rowId = $("table.stats-table tr td[data-code=" + codes[i] +"]").parent().attr("data-id");					
					$("a.bullet").eq(rowId - 1).addClass("active");
					$("input[data-id=" + (rowId - 1) + "]").attr("checked", true);
				}
			}
		}
		//Hide Cluster Items
		if (val == "hide") {
			codes = related.split("|");
			tableCodes = $("table.stats-table tr td:first").text();						
			
			for (i=0; i < codes.length; i++){
				if (tableCodes = codes[i]){
					$("table.stats-table tr td[data-code=" + codes[i] +"]").parent().hide();
					rowId = $("table.stats-table tr td[data-code=" + codes[i] +"]").parent().attr("data-id");
					$("a.bullet").eq(rowId - 1).removeClass("active");
					$("input[data-id=" + (rowId - 1) + "]").attr("checked", false);
				}
			}
		}
		tableRowCheck();
		selectAllCheck();
		hideQ07();
	}
//
//	Determine if cluster disclaimer needs to be shown
//	
	function disclaimerShow() {
		var row = $("tr[data-cluster=true]").is(":visible");
		if (row == true) {
			$("p.cluster").show();	
		} else {
			$("p.cluster").hide();
		}
	}
		

//
//	Clicking on the map
//
	mapArea.click(function(){
		stateDiv.removeClass("active").hide();
		selectionContainer.removeClass("visible").hide();
		
		id = $(this).attr("data-id");
		pdfUrl = $(this).attr("data-pdf");
	
		stateDiv.eq(id).addClass("active").show();
		selectionContainer.eq(id).addClass("visible").show();
		
		//Change PDF URL to match state selected
		$(".download").attr("href", "/app/webroot/files/marketReach/" + pdfUrl);
	});

//
//	Update table based on checkBox selection
//
	$(".selection input").change(function(){
		childId = $(this).attr("data-id");
		childId = (parseInt(childId) + parseInt(1));
		
		if ($(this).attr("checked")) {
			//when checked
			$("table.stats-table").show();
			$("table.stats-table tr:first").show();
			$("table.stats-table tr").eq(childId).show();
			$("#map-content a.bullet").eq(childId - 1).addClass("active");

			clusterItem = $(this).attr("data-cluster");
			showItems = $(this).attr("data-show");
			clusterCheck(clusterItem, showItems);
			disclaimerShow();
			selectAllCheck();
			return;
		}
		//If unchecking a cluster item
		if ($(this).attr("data-cluster")) {
			clusterItem = "hide";
			showItems = $(this).attr("data-show");
			clusterCheck(clusterItem, showItems);	
		}
		
		//when unchecked
		$("table.stats-table tr").eq(childId).hide();
		$("#map-content a.bullet").eq(childId - 1).removeClass("active");

		tableRowCheck();
		disclaimerShow();
		selectAllCheck();
		hideQ07();
	});

//
//	Click remove button 
//
	$(".remove").click(function(){
		id = $(this).parent().parent().attr("data-id");	
		idInput = id
		idInput = (parseInt(idInput) - parseInt(1));
		$("table.stats-table tr").eq(id).hide();
		$(".selection input[data-id='" + idInput +"']").attr('checked', false);
		$("#map-content a.bullet").eq(idInput).removeClass("active");

		tableRowCheck();
		disclaimerShow();
		if ($(this).parent().parent().attr("data-cluster")) {
			//console.log("parent cluster = true");
			clusterItem = "hide";
			showItems = $(this).parent().parent().attr("data-show")
			clusterCheck(clusterItem, showItems);
		}
		nswClusterCheck();
		selectAllCheck();
		hideQ07();
	});

//
//	Map Bullets activate call
//
	$("#map-content a.bullet").click(function(){
											  
	if ($(this).hasClass("active")){
		$(this).removeClass("active");	
		
		childId = $(this).attr("data-id");
		childId = (parseInt(childId) + parseInt(1));									  
		
		$(".selection input[data-id='" + (childId - 1) +"']").attr("checked", false);
		$("table.stats-table tr").eq(childId).hide();
		
		if ($(this).attr("data-cluster")) {
			clusterItem = "hide";
			showItems = $(this).attr("data-show");
			clusterCheck(clusterItem, showItems);
		}
		tableRowCheck();
		disclaimerShow();
		
		//N19 & N20 Cluster Hack
		if ( childId = 39 ) {
			$("#N19").attr("checked", false);
			$("#N20").attr("checked", false);
		}
		
	} else {
		$(this).addClass("active");	
		
		childId = $(this).attr("data-id");
		childId = (parseInt(childId) + parseInt(1));									  
		
		$(".selection input[data-id='" + (childId - 1) +"']").attr("checked", true);
		$("table.stats-table").show();
		$("table.stats-table tr:first").show();
		$("table.stats-table tr").eq(childId).show();
		
		clusterItem = $(this).attr("data-cluster");
		showItems = $(this).attr("data-show")
		clusterCheck(clusterItem, showItems);
		disclaimerShow();
		
		nswClusterCheck(19);
		//N19 & N20 Cluster Hack
		/*if ( childId == 39 ) {
			$("#N19").attr("checked", true);
			$("#N20").attr("checked", true);
		}*/

	}
	selectAllCheck();
	hideQ07();
	});
	
//
//	Fix for NSW overlay issue with Victoria
//	
	$(".vic-click").hide();
	
	$("area[data-id=3]").click(function(){
										
		$(".vic-click").show();
		
		$(".vic-click").click(function(){
			
			stateDiv.removeClass("active").hide();
			selectionContainer.hide();
			
			id = "4";
			pdfUrl = "VIC.pdf";
		
			stateDiv.eq(id).addClass("active").show();
			selectionContainer.eq(id).show();
			
			//Change PDF URL to match state selected
			$(".download").attr("href", "/app/webroot/files/marketReach/" + pdfUrl);
			
 	    });
	});
//	
//Hack For N19 & N20
//
	$("#N19").click(function(){
		nswClusterCheck(19);		
	});
	
	$("#N20").click(function(){
		nswClusterCheck(20);	
	});

	
	function nswClusterCheck(num) {
		
		$("#N20").attr("data-id", "40");
		//$("#N20").attr("data-id", "40");
	
		if (num == 19) {
		
			if ( $("#N19").is(":checked")) {
					$("#N20").attr("checked", true);
				} else {
					$("#N20").attr("checked", false);
			}
		} else if (num == 20) {
			if ( $("#N20").is(":checked")) {
					$("#N19").attr("checked", true);
				} else {
					$("#N19").attr("checked", false);
			}
		}
	}
//	
//Select All fucntionality
//

	//Add select all options to DOM
	$("#state-selection .selection form ul").append("<li class='all'><span class='code'>A00</span><label>Select all markets</label><input type='checkbox' /></li>");
	
	$("#state-selection .selection form ul li.all input").change(function(){
		
		if ($(this).attr("checked")) {
			visibleLi = $(this).parent().parent().find("li input");
			visibleLiSize = ((visibleLi.size()) - 1);
			visibleLi.attr(visibleLiSize);	
			for (i=0; i < visibleLiSize; i++){
				selectedDataId = visibleLi.eq(i).attr("data-id");
				$("a.bullet[data-id='" + selectedDataId + "']").addClass("active");	
				$("tr[data-id='" + (parseInt(selectedDataId) + 1) + "']").show();
			}
			$("table.stats-table").show();
			$("table.stats-table tr:first").show();
			visibleLi.attr("checked", true);
		} else {
			visibleLi = $(this).parent().parent().find("li input");
			visibleLiSize = ((visibleLi.size()) - 1);
			visibleLi.attr(visibleLiSize);	
			for (i=0; i < visibleLiSize; i++){
				selectedDataId = visibleLi.eq(i).attr("data-id");
				$("a.bullet[data-id='" + selectedDataId + "']").removeClass("active");	
				$("tr[data-id='" + (parseInt(selectedDataId) + 1) + "']").hide();
			}
			visibleLi.attr("checked", false);
		}
		
		tableRowCheck();
		hideQ07();
		
	});
	
	function selectAllCheck() {
		
		checkboxes = $("div.selection.visible form ul li input");
		checkboxesSize = (checkboxes.size() - 1);
		allVisible = 0;
		for (i=0; i < checkboxesSize; i++) {
			if (!checkboxes.eq(i).attr("checked")) {
				allVisible++;
			}
		}
		if (allVisible == 0) {
			$("div.selection.visible form ul li.all input").attr("checked", true);	
		} else {
			$("div.selection.visible form ul li.all input").attr("checked", false);
		}
	}

//
// Make sure Q07 data row is never shown
//
	function hideQ07() {
		$("tr[data-id=18]").hide();	
	}

	
}



////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Meet WP Users Flash
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var whoDetails;

function showDetail(name, dontUpdateFlash) {
	whoDetails.hide();
	$("#who-" + name.toLowerCase()).show();
	if (!dontUpdateFlash) getFlashMovieObject("flash_content").loadVideo(lookupNumber(name));
}
function updateFromFlash(number) {
	showDetail(lookupName(number), true);
}

var nameList = ["Erin", "Rebecca", "Sharyn", "Stephen", "Debra", "Graham", "Louise", "Oscar", "John", "Catherine", "Mary", "Leo"];
function lookupName(number) {
	return nameList[number - 1];
}
function lookupNumber(name) {
	for (var i = 0; i < nameList.length; i++) {
		var lookup = (["Erin", "Rebecca", "Sharyn", "Stephen", "Debra", "Graham", "Louise", "Oscar", "John", "Catherine", "Mary", "Leo"][i]).toLowerCase();
		if (name.toLowerCase() == lookup) {
			return i + 1;
		}
	}
}
function getFlashMovieObject(movieName)
{
	if (window.document[movieName]) 
	{
		return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft Internet")==-1)
	{
		if (document.embeds && document.embeds[movieName])
			return document.embeds[movieName]; 
	}
	else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
	{
		return document.getElementById(movieName);
	}
}

function whoAreThey() {
	var flashvars = {};
	flashvars.vidPath = "/app/webroot/flash/video/";
	flashvars.imgPath = "/app/webroot/img/wpUsers/";
	var params = {};
	params.allowScriptAccess = "always";
	params.wmode = "transparent";
	var attributes = {};
	attributes.name = "flash_content";
	swfobject.embedSWF("/app/webroot/flash/videoPlayer.swf", "flash_content", "460", "435", "9.0.0", "../_swf/expressInstall.swf", flashvars, params, attributes);
	
	whoDetails = $('#details .who-details');
	theSwf = getFlashMovieObject("flash_content");
	showDetail("louise", true);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Text Scrolller
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


function csvToArray(s) {
	var a = s.split(/[\f\r\n]+(?=(?:[^"]*"[^"]*")*(?![^"]*"))/g);
	for (var i = 0, il = a.length; i < il; i++) {
		a[i] = a[i].split(/,(?=(?:[^"]*"[^"]*")*(?![^"]*"))/g);
		for (var j = 0, jl = a[i].length; j < jl; j++) {
			a[i][j] = a[i][j].replace(/"(?!")/g, '');
			a[i][j] = a[i][j].replace(/["]{2}/g, '\"');
		}
	}
	return a;
}


function textScrollerInt() {
	$.ajax({
		   url:"index.php/newstickers/index",
		   dataType: "json",
		   success:function(data) {
				populatetextScroller(data);
		   },
		   error:function(error) {
			   alert("Error getting search results data: " + error);
		   }
		}
	);
}

function populatetextScroller(data) {
	$.each(data, function(index, array) {
		html = "<li>" + data[index]['Newstickers']['title'] + ", " + data[index]['Newstickers']['state'] + " ...</li>";
		$("ul#ticker").append(html);
	});
	
	textSlider();
	
}
function textSlider(){
	var container = $("ul#ticker");
	var containerLi = $("ul#ticker li");
	var size = containerLi.size();
	var width = 0;
	
	for (i=0; i < size; i++) {
		width = width + containerLi.width();	
	}
	
	//Set UL width
	container.css("width", width + "px");
	//var speed = (width / 11.5);
	//console.log(speed);
	var speed = 5000;
	speed *= size;
	
	width= width - 1000;

	container.animate({
		left: '-=' + width +'px'
	  }, 
	  speed, 
	  "linear", 
	  function() {
		 $("ul#ticker").css("left", 0);
		textSlider();
 	  });

}

