/* Initiates the task list on each page load, uses cookies to check the completion state */
function initTasks() {
	window.todo = {"tasks" : [	
			{"id" : "task1", "headline" : "Join our more birthdays community", "subhead" : "", "cta" : "Join &gt;", "link" : "/join", "completed" : getTask('task1')},
			{"id" : "task2", "headline" : "What does &quot;more birthdays&quot; mean to you?", "subhead" : "Share your thoughts in the candle gallery.", "cta" : "Add your message &gt;", "link" : "/birthday", "completed" : getTask('task2')},
			{"id" : "task3", "headline" : "Send a special birthday song.", "subhead" : "Musicians sing &quot;Happy Birthday&quot; for you to share.", "cta" : "Create &gt;", "link" : "/create/musician", "completed" : getTask('task3')},
			{"id" : "task4", "headline" : "Send an Art e-card.", "subhead" : "Use art to create a personalized birthday greeting.", "cta" : "Create &gt;", "link" : "/create/artist", "completed" : getTask('task4')},
			{"id" : "task5", "headline" : "Donate now to create more birthdays.", "subhead" : "Support the movement and help save lives.", "cta" : "Donate &gt;", "link" : "https://www.cancer.org/Involved/Donate/DonateOnlineNow/09BDay/index", "completed" : getTask('task5')},  
			{"id" : "task6", "headline" : "Get involved.", "subhead" : "Help us create a world with more birthdays.", "cta" : "Act &gt;", "link" : "/act", "completed" : getTask('task6')},
			{"id" : "task7", "headline" : "Help the NFL and ACS end breast cancer.", "subhead" : "Pledge to donate what your team scores.", "cta" : "Join with the NFL &gt;", "link" : "http://movement.morebirthdays.com/nfl", "completed" : getTask('task7')}
	] };
}


/* Used by initTasks() to retrieve a cookie value or set one as false if it doesn't exist */
function getTask(task) {
	if ($.cookie(task) == null) {
		$.cookie(task, 'false', {expires: 3650, path: '/'});
		return $.cookie(task);
	} else {
		return $.cookie(task);
	}
}


/* Updates the cart by reading a server side generated XML file based on the CI cart session */
/*function updateCart() {
	$.ajax({
		url: '/shop/xml',
		type: 'GET',
		dataType: 'xml',
		timeout: 10000,
		error: function(){
			myHTMLOutput = '';
			myHTMLOutput += '<li>Error, please refresh the page.<\/li>';
			$(".cart").html(myHTMLOutput);
		},
		success: function(xml) {
			myHTMLOutput = '<form action="http:\/\/www.shopcancer.org\/addToCart.aspx" method="get" target="_blank" >';
			myHTMLOutput += '<h1>Your Cart<\/h1><ul class="cart">';
			count = 1;
			$('item', xml).each(function(i) {
				row = $(this).find("row").text();
				qty = $(this).find("qty").text();
				subtotal = $(this).find("subtotal").text();
				name = $(this).find("name").text();
				sku = $(this).find("sku").text();
				myHTMLOutput += '<li><a class="remove" id="'+row+'" title="remove"><span>remove<\/span><\/a><span class="title">'+ name +'<\/span><span class="qty">Qty: '+ qty +'<\/span><span class="price">$ '+ subtotal +'<\/span>';
				myHTMLOutput += '<input type="hidden" name="item'+count+'" value="'+sku+'" \/>';
				myHTMLOutput += '<input type="hidden" name="qty'+count+'" value="'+qty+'" \/><\/li>';
				count++;
			});
			myHTMLOutput += '</ul>';
			$('cart', xml).each(function(i) {
				total = $(this).find("total").text();
				myHTMLOutput += '<span class="subtotal">subtotal &nbsp;&nbsp; $ '+total+'<\/span><br \/>';
			});
			//myHTMLOutput += '<button type="submit">Proceed to Checkout &gt;</button><\/form>';
			myHTMLOutput += '<input id="cart_submit" type="submit" name="action" value="Proceed to Checkout" \/><\/form>';
			if (count == 1) {
				$(".cart").html("<h1>Your Cart</h1><p>Shopping Cart is Empty</p>");
			} else {
				$(".cart").html(myHTMLOutput);
			}
			
			$('a.remove').click(function() {
				remove_from_cart = $.ajax({
					url: "/shop/remove/"+this.id+"/",
					success: function(data) {
						numItems = data;
						$('#itemCount').html(numItems);
						updateCart();
					}
				});
			});
		}
	});
}*/


/* Changes the candle color in the Your Birthday dropdown based on the cookie. */
function updateCandle() {
	candleColor = $.cookie("candleColor");
	if (candleColor) {
		$('.moreBirthdays').removeClass('grayCandle').addClass(candleColor+'Candle');
	}
}


/* Inserts the birthday into the heading and any relevant form fields based on cookie. */
function updateBirthday() {
	birthday = $.cookie("birthday");
	if (birthday) {
		$('.yourBirthday').html(birthday.replace(/\+/g, " "));
		$('input[name=birthday]').val(birthday.replace(/\+/g, " "));
	}
}


/* A quick function to write cookies, using this helps avoid duplicate cookies due to inconsistent pathing */
function complete(task) {
	$.cookie(task, 'true', {expires: 3650, path: '/'});
}


/* Adds next task to the C-FOP */
function getNextTask() {
	$(".init_task").hide();
	$(".next_task").hide();
	
	/* iterate through the task list looking for a false value */	
	for (var i in window.todo.tasks) {
		if (window.todo.tasks[i].completed == "false") {
			if(i == 1) {
				$(".init_task").show();
				$(".next_task").hide();
			} else {
				$(".next_task").show();
				$(".init_task").hide();
			}
			
			/* Set the HTML in the C-FOP */
			myHTMLOutput = '<div class="header">'+ window.todo.tasks[i].headline +'<\/div>';
			myHTMLOutput += '<p>'+ window.todo.tasks[i].subhead +'<\/p>';
			if(i == 4) {
				/* Open a new window for the donation link */
				myHTMLOutput += '<a target="_blank" class="donatelink" href="'+ window.todo.tasks[i].link +'">'+ window.todo.tasks[i].cta +'<\/a>';
			} else {
				myHTMLOutput += '<a href="'+ window.todo.tasks[i].link +'" class="cta">'+ window.todo.tasks[i].cta +'<\/a>';
			}
			$(".next_task").html(myHTMLOutput);
			
			break; /* Break out of the loop since we only need the first FALSE task */
		}
	}
}


/* Iterates through the task list on the Act page, checking the cookie id (which is the same as the li id), adds a 'checked' class if TRUE */
function updateChecklist() {
	// loop through each list item and compare id to cookie
	$('.nextSteps li').each(function(index) {
		if ($.cookie($(this).attr('id')) == "true") {
			$('#'+$(this).attr('id')).addClass('checked');
		}
	});
}


/*Pulls the product xml (on root) and assigns qty for limited items */
function insertQty() {
	/* Load XML */
	$.ajax({
		url: '/products_xml.php?item='+$('.limited').attr('id'),
		type: 'GET',
		dataType: 'xml',
		timeout: 10000,
		error: function(){
		},
		success: function(xml) {
			var qty;
			var sku;

			$('product', xml).each(function(i) {
				sku = $(this).find("sku").text();
				qty = $(this).find("availability").text();
			});
			if (qty && qty == 0) {
				/* Change 'Buy Now' link to 'Sold Out' if 0 remaining */
				//$("li#"+sku+" span.action").html("SOLD OUT");    Uncomment this line when you want SOLD OUT functionality working again.
			} else {
				/* insert qty into span tag */
				$("li#"+sku+" span.qty").html(qty+' remaining /');
			}
		}
	});
}


function trackIconSave(destination) {
	switch(destination) {
		case "desktop":
			_gaq.push(['_trackEvent', 'Custom_Icon', 'Desktop'],['mi._trackEvent', 'Custom_Icon', 'Desktop']);
		break;
		case "facebook":	
			_gaq.push(['_trackEvent', 'Custom_Icon', 'Facebook'],['mi._trackEvent', 'Custom_Icon', 'Facebook']);
		break;
	}
}

function formatNumberCommas(num) {
    num += '';
    x = num.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return (x1 + x2);
}

function viewsCount(data)
{
   var viewCount = data.entry.yt$statistics.viewCount;
   $(".shareVideo .number span").text(formatNumberCommas(viewCount));
  }

$(document).ready(function() { 

	// Initialize
	initTasks();
	getNextTask();
	updateCandle();
	updateBirthday();
	updateChecklist();


	// Called if an item in the ACT task list is clicked.
	$('.checkitem').click(function() {
		var cookie = $(this).parent().attr('id'); // Get the cookie name, which also happens to be the parent list id.
		if(cookie == 'more_ways') {$(this).attr('target','_blank');} // For 'More Ways' open a new window (no cookie required)
		if(cookie.substr(0,3) == 'ext') { // If the first three characters are ext then open in a blank window and set cookie to TRUE
			$(this).attr('target','_blank');
			complete(cookie);
			if(cookie == "ext_donate") {
				complete("task5");
			}
			updateChecklist();
		}
	});
	
	
	// Donate is tracked with two cookies, one for the C-FOP and one for the ACT page. Ugly I know.
	$('.donatelink').click(function() {
		complete('task5');
		complete('ext_donate');
		updateChecklist();
	});
	
	
	// The initial remove from cart function, also reloaded with every page updateCart()
	/*$('a.remove').click(function() {
		remove_from_cart = $.ajax({
			url: "/shop/remove/"+this.id+"/",
			success: function(data) {
				numItems = data;
				$('#itemCount').html(numItems);
				updateCart();
			}
		});
	});*/

});

/***************************************/


function home_hide() {
	// hide content
	// $('.wrapper').css('visibility', 'hidden');
	// $('#container').css('visibility', 'hidden');
	// this had to go inline to the homepage view so there is no blinking
}

function home_show() {
	$('.wrapper').css('visibility', 'visible');
	$('#container').css('visibility', 'visible');
	$('.wrapper').fadeIn('slow');
	$('#container').fadeIn('slow');
}

function activateSelectMusician() {
	if (swfobject.getFlashPlayerVersion().major >= 9) {
		init_home_feature_musician();
		var params = {
			wmode : "transparent",
			allowScriptAccess : "always"
		};
		var vars = {
			image : "/images/staticFeatures/home-wrapper.jpg",
			callback_unwrappingReady : "flashCallback_unwrappingReady",
			callback_unwrappingComplete : "flashCallback_unwrappingComplete",
			call_unwrap : "flashCall_unwrap"
		};
		swfobject.embedSWF("swf/peel.swf", "peel", "932", "356", "9.0.0", null,
				vars, params, null);
	} else {
		flashFallback();
	}
}

function peel_remove() {
	$('#peel').remove();
}

function flashFallback() {
	peel_remove();
	init_home_feature_musician();
	content_show();
}

function peel_unwrap() {
	if ($('#peel')[0] != undefined
			&& $('#peel')[0].flashCall_unwrap != undefined) {
		$('#peel')[0].flashCall_unwrap(1250);
	} else {
		flashFallback();
	}
}

function content_show() {
	home_show();
}

function flashCallback_unwrappingComplete() {
	peel_remove();
}

function flashCallback_unwrappingReady() {
	content_show();
	if ($.cookie('task1') == "true") {
		peel_unwrap();
	}
}

function init_home_feature_musician() {
	$('select').uniform();
	$('.musicianPicker select').bind(
			'change',
			function() {
				var itemValue = $(this).attr('value');
				var itemText = $("option[value='" + itemValue + "']", this)
						.text();
				$('#musicianLabel span').html(itemText);
				$('.musicianPicker a.create').attr('href',
						'/create/musician/' + itemValue.split("_")[1]);
				$('#musicianVideo').video({
					xmlPath : '/feed/video/' + itemValue + '/main',
					noShare : true
				});
			});
	$('.musicianPicker select').val('235_jennifer-hudson').trigger('change');
	$.uniform.update();
}



function activateArtHover() {
	$('.about #rotatorContent .item').hover(function() {
		$('.fact .message', this).fadeOut('slow');
		$('.fact .candle', this).fadeOut('slow');
		$('.fact .bgColor', this).fadeOut('slow');
	}, function() {
		$('.fact .message', this).fadeIn('slow');
		$('.fact .candle', this).fadeIn('slow');
		$('.fact .bgColor', this).fadeIn('slow');
	});
}

/*
* Global
*/
function activatePopJoin()
{
	//alert("ss");
	$('a[rel="popJoin"]').click(function(){
		//alert($(this).html());
		modal_join_show($('#modal_join'));
		return false;
	});
}
var show_modal_on_home = 'falsedede';
var isOnHome = 'false';
/**
 * init_home extended
 */
if (init_home != undefined) {
	var super_init_home = init_home;
	var init_home = function() {
		//
		home_hide();
		// proceed with oryginal init_home
		super_init_home();
		// lets activate new feature box
		activateSelectMusician();
		//
	}
}

/**
 * about page
 */
if (init_about != undefined) {
	var super_init_about = init_about;
	var init_about = function() {
		super_init_about();
		activateArtHover();
	}
}

$(document).ready(function(){
	if(isOnHome == 'true')
	{
		show_modal_on_home = 'true';
	}
	modal_join_init();
	activatePopJoin();
});

