 $oldAddName   = ""; 
 $oldAddJob   = "";  		 
 $oldAddEmail  = "";  
 $oldAddSlogan = "";  
 $oldAddGender = ""; 
 $oldAddReason = "";

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/**	
 * @author nick
 */

$join = false;

function loadXML() {
	
	if (typeof $currentXML != 'undefined') {
		xml = parseInt($currentXML);
		xml++;
	} else {
		xml = 0;
	}

	$.ajax({
		type: "GET",
		url: "xml/persons"+xml+".xml",
		dataType: "xml",
		success: parseXml
	});

}

function parseXml(xml)
{
	// Find every person
	$counter = 0;
	$popupCounter = 0;
	$total = $(xml).find("persons").attr("total");
	$currentXML = $(xml).find("persons").attr("currentXML");	
	$xmlFiles = $(xml).find("persons").attr("xmlFiles");			
	
	if ($currentXML == ($xmlFiles-1)) {$("a.loadXML").hide();}
	
	$extra = "";
	$you = $.cookie('you');
		
	$(xml).find("person").each(function()
		{
		if ($(this).attr("gender")== 0) {$gender = "man";}
		if ($(this).attr("gender")== 1) {$gender = "vro";}
		$job = $(this).find("job").text()
		if ($job == "") {$jobTxt = "";}
		if ($job != "") {$jobTxt = ", "+ $job;}

		if ($you == $(this).attr("id")) {
			$extra = "<span class='you'></span>";
		} else {
			$extra = "";
		}
		
		$dup = $("ul#show").find("li#"+$(this).attr("id")+"");
		if ($("ul#show li#"+$(this).attr("id")+"").length == 0) {
			$("ul#show").prepend("<li id=" + $(this).attr("id") + " class=\"" + $gender + $(this).attr("reason") + "\" onmouseover=\"showContent("+ $(this).attr("id") +")\" onmouseout=\"hideContent("+ $(this).attr("id") +")\" ><div class=\"" + $gender + $(this).attr("reason") + "\">"+$extra+"<div class=\"popup\"><span class='wrap'><span class='header'>Ook voor een flexibele AOW want:</span><span class='slogan'>" + $(this).find("slogan").text() + "</span><span class='name'>" + $(this).find("name").text() + "</span><span class='job'>" + $jobTxt + "</span></span><span class='footer' onclick='openJoinHidePopup("+ $(this).attr("id") +")'>Ook voor een flexibele AOW?, Sluit je aan!</span></div></div></li>");
	
			$counter++;
		}
	});
	
	lineUp();
	$("ul#show li div.popup").hide();
	
}

function lineUp() {
	$("li.space").remove();
	$("li").removeClass("left");
	$("li").removeClass("right");
	$counter = 0;
	$popupCounter = 0;
	$("ul li").each (function()
	{
		$counter++	
		if ($popupCounter == 15)
		{
			$popupCounter = 0;
		}
		if ($popupCounter < 7)
		{		
			$(this).addClass("left");
		} else {
			$(this).addClass("right");
		}
		$popupCounter++	
		
		if ($counter == 15)
		{
			$(this).after("<li class='space'><div></div></li>");
			
		}
		if ($counter == 29)
		{		
			$counter = 0;
			$popupCounter = 0;
		}				
	});	
}
	
function setNew(id, reason, name, slogan, gender, job)
{
	if (gender== 0) {$genderTxt = "man";}
	if (gender== 1) {$genderTxt = "vro";}
	if (job == "") {$jobTxt = "";}
	if (job != "") {$jobTxt = ", "+ job;}
	
	$.cookie('you', id);

	$extra = "<span class='you'></span>";
	$("ul#show").append("<li id="+id+" class='"+$genderTxt+reason+"' onmouseover=\"showContent("+id+")\" onmouseout=\"hideContent("+id+")\" >"+$extra+"<div class='"+$genderTxt+reason+"'><div class='popup'><span class='wrap'><span class='header'>Ook voor een flexibele AOW want:</span><span class='slogan'>"+slogan+"</span><span class='name'>"+name+"</span><span class='job'>"+$jobTxt+"</span></span><span class='footer' onclick='openJoinHidePopup("+ id +")'>Ook voor een flexibele AOW?, Sluit je aan!</span></div></div></li>");
	$last = $("ul#show li:last");
	$last.hide();
	$("div#join").hide();	
}

function space()
{
}

function hideReason($reasonID)
{
	//alert("showReason: " + $reasonID);
	$("li.man"+$reasonID).removeClass('active');
	$("li.vro"+$reasonID).removeClass('active');
}

function showReason($reasonID)
{
	//alert("showReason: " + $reasonID);
	$("li.man"+$reasonID).addClass('active');
	$("li.vro"+$reasonID).addClass('active');
}

function checkFirstPerson()
{
	$first = $("ul#show li:last");
	if ($first.length == 0){
		$(this).delay(1000,function(){
			checkFirstPerson();
		});		
	} else {
		jsReady = true;			
	}		
}

function getFirstPerson()
{
	$lastSpaceTest = $("ul#show li:last");	
	$lastSpaceTestReason = $lastSpaceTest.attr('class');
	
	if ($lastSpaceTestReason == "space") {
		$("ul#temp li.space:last").remove();
		$("ul#show li.space:last").remove();
		
	}
	
	$last = $("ul#show li:last");	
	$lastID = $last.attr('id');
	$lastReason = $last.attr('class');
	$lastReasonID = $lastReason.charAt(3);
	$lastName = $last.find("span.name").text();
	$job = $last.find("span.job").text();
	$job = $job.slice(2);
	$lastGenderText = $lastReason.substr(0,3);
	if ($lastGenderText == "man") {$lastGender = 0};
	if ($lastGenderText == "vro") {$lastGender = 1};
	$lastSlogan = $last.find("span.slogan").text();
	$("ul#temp").prepend($last);
	$last.hide();
	
	// Send result to Flash
//	alert($lastID +'-'+ $lastReasonID +'-'+ $lastName +'-'+ $lastGender +'-'+ $lastSlogan +'-'+ $job);
	setFirstPerson($lastID, $lastReasonID, $lastName, $lastGender, $lastSlogan, $job);		
}


function showLastPerson(personID)
{
	//alert(personID);
	$first = $("ul#temp li#"+personID);		
	$("ul#show").prepend($first);
	$first.show();
	$("ul li div div.popup").hide();

	lineUp();

}

$("ul li").click(function() {
    // find out index of img's parent <th> in its own <tr>

});



 
function showContent(id)
{
	$("ul li#"+id+" div.popup").show();		
}

function hideContent(id)
{
	$("ul li#"+id+" div.popup").hide();		
}

function openJoin()
{
	if ($join == false)
	{
		$("div#join div#intro").show();				
	}	
	if ($join == true)
	{	
		$("div#intro").hide();
		$("div#join form").hide();		
		$("div#thanks").show();
	}
	$("div#join form").hide();	
	$("div#join").show();		

}

function openJoinHidePopup(id)
{
	if ($join == false)
	{
		$("div#join div#intro").show();				
	}	
	if ($join == true) {
		$("div#intro").hide();
		$("div#join form").hide();		
		$("div#thanks").show();
	}
	$("div#join form").hide();	
	$("ul li#"+id+" div.popup").hide();	
	$("div#join").show();		
}

function openSendFriend()
{
		$("div.sendWrap").show();
		$("div#sendThanks").hide();					 
		$("div#send").show();
		$("div#send form").show();
}

function showThanks() {
	$("div#join form").hide();	
	$("div#thanks").show();
}

function closeThanks() {
	$("div#join").hide();	
	$("div#thanks").hide();	
	
	if ($join == false) {
		setNew($insertID,$addReason,$addName,$addSlogan,$addGender,$addJob);
	}
	$join = true;
}
   
$(document).ready(function()
{	
   
	$("form#sendForm").submit(function()
	{  
		 // we want to store the values from the form input box, then send via ajax below  
		 var fromName = $('#fromName').attr('value');  		 
		 var email    = $('#sendEmail').attr('value');  
		 var toName   = $('#toName').attr('value');
		 	
		 if ((fromName != "")&(email != "")&(toName != "")) {
			 
			 $("form#sendForm").hide();
			 
			 $.ajax({  
				 type: "POST",  
				 url: "includes/send.php",  
				 data: "toName="+ toName +"&email="+ email +"&fromName="+ fromName,  
				 success: function($var){  			
					 $('#fromName').val('');
					 $('#sendEmail').val('');
					 $('#toName').val('');	
					 
					 $("div.sendWrap").hide();
					 $("div#sendThanks").show();
				 }  
			 });  
		 } else {
			 alert("Verplichte velden zijn niet ingevuld.")
		 }
		 
		 return false;  
     });

	$("form#addPerson").submit(function()
	{  
		
		 // we want to store the values from the form input box, then send via ajax below  
		 $addName   = $('#name').attr('value');
		 $addJob   = $('#job').attr('value');		 
		 $addEmail  = $('#email').attr('value');
		 $addSlogan = $('#slogan').attr('value');
		 $addGender = $("label input[name='gender']:checked").val(); 
		 $addReason = $("label input[name='reason']:checked").val(); 	

		 if ($addReason == 0) {$addSlogan = $reason0;}
		 if ($addReason == 1) {$addSlogan = $reason1;}
		 if ($addReason == 2) {$addSlogan = $reason2;}		 
			 
		 if (($addName != "")&($addGender != undefined)&($addEmail != "")&($addReason != undefined)&($addName != $oldAddName)&($addJob != $oldAddJob)&($addEmail != $oldAddEmail)&($addSlogan != $oldAddSlogan)&($addGender != $oldAddGender)&($addReason != $oldAddReason)) {			 			 
			 			 
			 $oldAddName   = $addName; 
			 $oldAddJob   = $addJob;  		 
			 $oldAddEmail  = $addEmail;  
			 $oldAddSlogan = $addSlogan;  
			 $oldAddGender = $addGender; 
			 $oldAddReason = $addReason;
			 
			 $addName   = $addName.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi,'');  
			 $addJob   = $addJob.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi,'');  		 
			 $addEmail  = $addEmail.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi,'');  	 
			 $addSlogan = $addSlogan.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi,'');  
			 
			 $("div#join form").hide();	
			 
			 $.ajax({  
				 type: "POST",  
				 url: "includes/insert.php",  
				 data: "name="+ $addName +"&job="+ $addJob +"&email="+ $addEmail +"&slogan="+ $addSlogan+"&reason="+ $addReason+"&gender="+ $addGender,  
				 success: function($var){  			
					 $('#name').val('');
					 $('#job').val('');
					 $('#email').val('');
					 $('#slogan').val('');
					 
					 $insertID = $var;					 

					 showThanks();
					 
				 }  
			 });  
		 } else {
			 alert("Verplichte velden zijn niet ingevuld.")
		 }
		 
		 return false;  
     });

	$("a.reason0").click(function () {
		showReason(0);
	});
	$("a.reason1").click(function () {
		showReason(1);
	});
	$("a.reason2").click(function () {
		showReason(2);
	});	
	$("a.reason3").click(function () {	
		showReason(3);
	});	

	$("a.ready").click(function () {	
		checkFirstPerson();
//		jsReady = true;
	});	

	$("a.getFirst").click(function () {
		getFirstPerson();
	});		
	$("a.showLast").click(function () {
		showLastPerson();
	});	
	$("a.setNew").click(function () {
		setNew("22","1","naaamm","een heel verhaal");
	});	
	$("a.openJoin").click(function () {
									$join = false;
		openJoin();
	});	
	$("div#intro a.closeJoin").click(function () {
		$("div#join").hide();
	});		
	$("div#intro img.introButton").click(function () {
		$("div#intro").hide();
		$("div#join form").show();
	});			
	$("div#join form a.closeJoin").click(function () {
		$("div#join").hide();
	});	
	
	$("div#send a.closeJoin").click(function () {
		$("div#send").hide();
	});		

	$("div#join").hide();
	$("div#thanks").hide();
	
	$("span.footer").click(function () {
		openJoin();
	});		
	
	$("a.loadXML").click(function () {
		loadXML();
	});			

	$("div#thanks img").click(function () {
		closeThanks();
	});	
	
	$("div#sendThanks a.openSend").click(function () {
		openSendFriend();
	});	
	
	$("a.openSend").click(function () {
		openSendFriend();
	});	
	
	loadXML();
	
	checkFirstPerson();

});

