$(function() {


var cookieList = function(cookieName) {
//When the cookie is saved the items will be a comma seperated string
//So we will split the cookie by comma to get the original array
var cookie = $.cookie(cookieName);
//Load the items or a new array if null.
var items = cookie ? cookie.split(/,/) : new Array();

//Return a object that we can use to access the array.
//while hiding direct access to the declared items array
//this is called closures see http://www.jibbering.com/faq/faq_notes/closures.html
return {
    "add": function(val) {
    
	    // check duplicates
	    for (i=0; i<items.length; i++) {
	    	var dupe = items[i];
	    	if (val==dupe) {
	    		var foundDuplicate = 1;
				alert("This item has already been favourited");
	    		break;
	    	}   	
	    }
	    
	    // add item if there's no duplicates
	    if(!foundDuplicate){
	    	 //Add to the items.
	        items.push(val);
	        //Save the items to a cookie.
	        $.cookie(cookieName, items, { expires: 9999 });
	    }
       
    },
    "clear": function() {
        //clear the cookie.
        $.cookie(cookieName, null);
    },
    "items": function() {
        //Get all the items.
        return items;
    },
    "total": function() {
    	//get total item
    	return items.length;
    },
    "del": function(val) {
    	//get item location/position in array
    	//target = items.indexOf(val); <-- dumb IE can't use this had to take a longer detour
    	for (i=0; i<items.length; i++) {
    		if(val==items[i]) {
    			target = i;
    			break;
    		}
    	}

    	if(target>=0) { // check if item exist in array just incase of bug
    		//del item
    		items.splice(target,1);
	    	//update cookie
	    	$.cookie(cookieName, items);
    	}
    	
    }
    
  }
}

// set new cookieList for favourite HnL
var favHnL = new cookieList("favHnL"); // fav House & Land
var favDis = new cookieList("favDis"); // fav Display
var favHse = new cookieList("favHse"); // fav House


function resetFav() {
	favHnL.clear();
	favDis.clear();
	favHse.clear();
}


function favCount(totalHnL, totalDisplay, totalHouse) {
	if (totalHnL == null) {
		totalHnL = 0;
	}
	if (totalDisplay == null) {
		totalDisplay = 0;
	}
	if (totalHouse == null) {
		totalHouse = 0;
	}

	return totalHnL + totalDisplay + totalHouse;
}

// auto update total Collection on page load
function updateTotalCollection() {
/* 	$('.favCollection').css({backgroundColor: '#dd0026'}).animate({backgroundColor: '#f3f3f3'}, 1000 ); */
/* 	$('#cTotal').slideUp().css({color: 'red'}).text(favCount(favHnL.total(),favDis.total(),favHse.total())).slideDown().animate({color:'#666'}, 500); */
	$('#cTotal').text(favCount(favHnL.total(),favDis.total(),favHse.total()));
};
updateTotalCollection();


// show plus 1
function plusOne() {
	$('#favNotice').animate({"bottom":"30px"},50).animate({"bottom":"25px"},100);
	$('#plus1').show().delay(2000).fadeOut('3000');
	$('#minus1').hide();
}
function minusOne() {
	$('#favNotice').animate({"bottom":"30px"},50).animate({"bottom":"25px"},100);
	$('#minus1').show().delay(2000).fadeOut('3000');
	$('#plus1').hide();
}


// check cookie and hide all unnecessary buttons

for (i=0; i<favHnL.total(); i++) {

	var id = favHnL.items()[i];
	$('.fav[name=delHnL][href='+id+']').removeClass('hidden');
	$('.fav[name=favHnL][href='+id+']').addClass('hidden');
	
}

for (i=0; i<favHse.total(); i++) {

	var id = favHse.items()[i];
	$('.fav[name=delHse][href='+id+']').removeClass('hidden');
	$('.fav[name=favHse][href='+id+']').addClass('hidden');
	
}

for (i=0; i<favDis.total(); i++) {

	var id = favDis.items()[i];
	$('.fav[name=delDis][href='+id+']').removeClass('hidden');
	$('.fav[name=favDis][href='+id+']').addClass('hidden');
	
}


function statTrack(action, id) {
	//AJAX record favourite
			
	$.ajax({
		type: 'POST',
		url: 'includes/functions.php',
		data: {log: action, itemID: id},
		
		success: function(result) {
			//alert('success');
			//alert(result);
		}
	});
	
}


// FAVOURITE COLLECION FUNCTIONALITY
$('.fav').click(function() {
	var id = $(this).attr('href');	
	var action = $(this).attr('name');
	
	switch (action) {
		case "favHnL":
			// add cookie
			favHnL.add(id);		
			$(this).addClass('hidden');
			$(this).next('a').removeClass('hidden');
			plusOne();
			//favNotification('House & Land package has been added into your collection');
			statTrack(action, id);
			
		break;
		
		case "delHnL":
			// del cookie
			favHnL.del(id);
			$(this).addClass('hidden');
			$(this).prev('a').removeClass('hidden');
			minusOne();
			//delNotification('Item has been successfully removed');
		break;
		
		case "favHse":
			// add cookie
			favHse.add(id);		
			$(this).addClass('hidden');
			$(this).next('a').removeClass('hidden');
			plusOne();
		//	favNotification('Favourite home has been added');
			
			statTrack(action, id);
			
		break;
		
		case "delHse":
			// del cookie
			favHse.del(id);
			$(this).addClass('hidden');
			$(this).prev('a').removeClass('hidden');
			minusOne();
		//	delNotification('Item has been successfully removed');
		break;
		
		case "favDis":
			// add cookie
			favDis.add(id);	
			$('.fav[name=delDis][href='+id+']').removeClass('hidden');
			$('.fav[name=favDis][href='+id+']').addClass('hidden');	
			plusOne();
			//favNotification('Favourite displays on sale has been added');
			
			statTrack(action, id);
			
		break;
		
		case "delDis":
			// del cookie
			favDis.del(id);
			$('.fav[name=delDis][href='+id+']').addClass('hidden');
			$('.fav[name=favDis][href='+id+']').removeClass('hidden');	
			minusOne();
			//delNotification('Item has been successfully removed');
		break;
	}
	
	// update total collection and update collection drawer incase its open
	updateTotalCollection();
	$('#favDrawer').load('includes/favDrawer.php');
	
	
	return false;
});

// show favHnL
/*
$('#favCollection').click(function() {
	// alert all cookie
	alert(favHnL.items());
	alert(favHse.items());

	return false;
});
*/

// fav icon swap image/mouse over
$('.favIcon').mouseover(function() {
	$(this).attr('src','images/favover.png');
});
$('.favIcon').mouseout(function() {
	$(this).attr('src','images/unFav.png');
});

function favNotification(note) {
	$.gritter.add({
		// (string | mandatory) the heading of the notification
		title: 'FAVOURITE',
		// (string | mandatory) the text inside the notification
		text: note,
		// (string | optional) the image to display on the left
		image: 'images/fav.png',
		// (bool | optional) if you want it to fade out on its own or just sit there
		sticky: false, 
		// (int | optional) the time you want it to be alive for before fading out
		time: '1000'
	});
}

function delNotification(note) {
	$.gritter.add({
		// (string | mandatory) the heading of the notification
		title: 'FAVOURITE REMOVED',
		// (string | mandatory) the text inside the notification
		text: note,
		// (string | optional) the image to display on the left
		image: 'images/unFav.png',
		// (bool | optional) if you want it to fade out on its own or just sit there
		sticky: false, 
		// (int | optional) the time you want it to be alive for before fading out
		time: '1000'
	});
}

});
