var cookie_id = 'itunes_promo_code';

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 'none';
}
function getCode() {

	var arg1 = 'get_pc';
	var arg2 = readCookie(cookie_id);

	$.getJSON("promo_codes/pc.php",{arg1: arg1, arg2: arg2}, function(j){

			if (j[0].error_num == '0')  {
				$('#itunes-button').html(j[0].html);
				if (arg2 == 'none') {
					createCookie(cookie_id,j[0].code,100);
				}
			}
			else $('#itunes-button').html(j[0].html); // set error message
		}
	);
}

function redeemCode() {

	var arg1 = 'set_pc';
	var arg2 = readCookie(cookie_id);
	$.getJSON("promo_codes/pc.php",{arg1: arg1, arg2: arg2}, function(j){

			if (j[0].error_num == '0')  {
				window.location = 'https://phobos.apple.com/WebObjects/MZFinance.woa/wa/freeProductCodeWizard?code='+arg2;
			}
		}
	);
}

$(document).ready(function() {
		$('#pc-link').click(function() {
			 getCode();
		});

		if (readCookie(cookie_id) != 'none') getCode();

})
