/* Extends */
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    };
    return size;
};
function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/in_array    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {                return true;
            }
        }
    }
     return false;
}

/*
	Function to display all cats from given location
	Outputs to html element with id="cats-available"
*/
var displayCatsByLocation = (function(idx) {
	if (typeof(idx) == 'undefined') { return false; };
	
	var tgt = $('#cats-available');
	tgt.html('<h1>Please wait...<br /><br>Retrieving information.</h1>'); // Set wait msg

	// Info is in master text file, generated by PHP
	window.setTimeout(function(){
		$.getJSON('/php/output/availableCats-'+idx+'.txt',
			{},
			function(data) {
				if (data['ok']) {
					if (data['cats'][idx].length > 0) {
						// Cats exist in this location
						var toAppend=''; // HTML container
	
						$.each(data['cats'][idx],function(n) {
 							if (n%3 == 0) { // Add row container
								toAppend += '<div class="cat-row">';
							};
							toAppend += '\
<div class="cat">\
<a href="'+this['url']+'" title="Read more about '+this['name']+' on PetFinder" target="PETWIN"><img src="'+this['photoURL']+'" width="125" border="0" align="top" alt="'+this['name']+'" title="Read more about '+this['name']+' on PetFinder" /><br />\
'+this['name']+'</a>\
<p>'+this['desc']+'</p>\
</div>\
';
							if (n%3 == 2) { // Close cat-row & clear after 3 entries
								toAppend += '<div class="clearer"></div></div>';
							};
						});
						toAppend += '<div class="clearer"></div>';
						
						tgt.html(''); // Clear wait message
						tgt.append(toAppend); // Add cats
					}
					else {
						tgt.html('<p>No cats are currently available.</p>');
					};
				};
			}
		);
	}, 1000); // Set delay to show processing
});


/*
	Function to display cats at random for homepage
	Outputs to html element with id="featured-cats"
*/
var displayHomepageFeaturedCats = (function() {

	var limit = 6; // Number of cats to display
	var tgt = $('#featured-cats');
	tgt.html('<h1>Please wait...<br /><br>Retrieving information on featured cats.</h1>'); // Set wait msg

	// Info is in master text file, generated by PHP
	window.setTimeout(function(){
		$.getJSON('/php/output/availableCats-FosterHomes.txt',
			{},
			function(data) {
				if (data['ok']) {
					
					var locationCount = Object.size(data['cats']);

					// Set numeric keys x1, x2... for each location
					for (var x=1; x<=locationCount; x++) {
						for (var k in data['cats']) {
							eval("var x"+x+" = '"+k+"';");
							x++;
						};																  
					};

					var cnt = 0; // Counter
					var tries = 0; var maxTries = (limit*10); // Throttle
					var cats = []; // Output holder
					if (tries<maxTries) {
						while (cnt<limit) {						
							var r1 = Math.floor(Math.random()*locationCount)+1; // Range: 1-locationCount
							eval("var loc = x"+r1+";"); // Get location string as key
							var r2 = Math.floor(Math.random()*data['cats'][loc].length); // Range: 0<length
							if (data['cats'][loc][r2] && (!in_array(data['cats'][loc][r2], cats))) {
								cats.push(data['cats'][loc][r2]); // Push to output
								cnt++; // Flag success
							};
							tries++;
						};
					};
					if (cats.length>0) {
						tgt.html(''); // Clear wait message
						$.each(cats,function(n){
							tgt.append('\
<div class="cat">\
<a href="'+this['url']+'" title="Read more about '+this['name']+' on PetFinder" target="PETWIN"><img src="'+this['photoURL']+'" width="75" border="0" align="top" alt="'+this['name']+'" title="Read more about '+this['name']+' on PetFinder" /><br />\
'+this['name']+'</a>\
</div>\
');
						});
						tgt.append('<div class="clearer"></div>');
					}
					else {
						tgt.html('<p>No featured cats are currently available.</p>');
					};
				};
			}
		);
	}, 1000); // Set delay to show processing
});


