//<![CDATA[

jQuery(function() {

$('#location').autocomplete({ 
	serviceUrl:'../../includes/findTowns.php',
	minChars:2, 
	delimiter: /(,|;)\s*/, // regex or character
	maxHeight:400,
	width:300,
	deferRequestBy: 0, //miliseconds
	// params: { country:'Yes' }, //aditional parameters
	// callback function:
	onSelect: function(value, data){ $("#zipcode").val(data); },
	// local autosugest options:
	// lookup: ['January', 'February', 'March', 'April', 'May'] //local lookup values 
	});

});

$(document).ready(function(){


	// Start of snipplet to update the jQuery live() method and add the "blur" event
	//*****************************************************************************************************************
	(function(){
	
	    var special = jQuery.event.special,
	        uid1 = 'D' + (+new Date()),
	        uid2 = 'D' + (+new Date() + 1);
	
	    jQuery.event.special.focus = {
	        setup: function() {
	            var _self = this,
	                handler = function(e) {
	                    e = jQuery.event.fix(e);
	                    e.type = 'focus';
	                    if (_self === document) {
	                        jQuery.event.handle.call(_self, e);
	                    }
	                };
	
	            jQuery(this).data(uid1, handler);
	
	            if (_self === document) {
	                /* Must be live() */
	                if (_self.addEventListener) {
	                    _self.addEventListener('focus', handler, true);
	                } else {
	                    _self.attachEvent('onfocusin', handler);
	                }
	            } else {
	                return false;
	            }
	
	        },
	        teardown: function() {
	            var handler = jQuery(this).data(uid1);
	            if (this === document) {
	                if (this.removeEventListener) {
	                    this.removeEventListener('focus', handler, true);
	                } else {
	                    this.detachEvent('onfocusin', handler);
	                }
	            }
	        }
	    };
	
	    jQuery.event.special.blur = {
	        setup: function() {
	            var _self = this,
	                handler = function(e) {
	                    e = jQuery.event.fix(e);
	                    e.type = 'blur';
	                    if (_self === document) {
	                        jQuery.event.handle.call(_self, e);
	                    }
	                };
	
	            jQuery(this).data(uid2, handler);
	
	            if (_self === document) {
	                /* Must be live() */
	                if (_self.addEventListener) {
	                    _self.addEventListener('blur', handler, true);
	                } else {
	                    _self.attachEvent('onfocusout', handler);
	                }
	            } else {
	                return false;
	            }
	
	        },
	        teardown: function() {
	            var handler = jQuery(this).data(uid2);
	            if (this === document) {
	                if (this.removeEventListener) {
	                    this.removeEventListener('blur', handler, true);
	                } else {
	                    this.detachEvent('onfocusout', handler);
	                }
	            }
	        }
	    };
	
	})();
	// End of code to update the jQuery live() method and add the "blur" event


	// Show or Hide the welcome message !

	// x will exist if user already asked to remove the message
	var x = readCookie('sessionWelcomeMsg')
	if (!x) {
		$('div.topmessage').show();
	}

	// If user asks for, we remove the message and create a cookie 
	$('#closeTopMsg').click(function() {
		$('div.topmessage').css('background-color', 'yellow');
		$('div.topmessage').fadeOut('slow');
		createCookie('sessionWelcomeMsg','hide',7)
	});
	//eraseCookie('sessionWelcomeMsg');




	// Fill out info about the last startups
	$(function() {

		$('#lastAdditions').html('Loading...');

		$.get("../../includes/findCompanies.php", { format:'xmlfeed' } , function(data) {
			size = parseInt($(data).find("size").text());
		
			myHTMLOutput = '';
			i = 1;
		
			$('company', data).each(function(i) {
				companyName = $(this).find("name").text();
				companyWebsite = $(this).find("website").text();
				companyLocation = $(this).find("location").text();
				companyZipcode = $(this).find("zipcode").text();

				nbrOfFounders = $(this).find("nbroffounders").text();

				myHTMLOutput += '<a href="'+companyWebsite+'">'+ companyName +'</a><br>';
				myHTMLOutput += '<div style="margin-left:10px; margin-bottom: 0px;">In '+ companyLocation +', '+ companyZipcode +'<br>';

				companyFounders = '';
				separator = '';
				for (j=1;j<=nbrOfFounders;j++) {
					if (nbrOfFounders == 1) {separator = '';} else if (j == nbrOfFounders) {separator = '';} else {separator = ', ';}
					companyFounders += $(this).find("founder"+j).text();
					companyFounders += separator;
				}

				myHTMLOutput += 'Founded by '+ companyFounders +'</div>';
				
				i++;
				return(i != 5);
			});
			
			myHTMLOutput += '';
			$('#lastAdditions').html(myHTMLOutput);
		  })
	});


	// Find out information about a founder using the Twitter API
	$("input[id*=founderstwitter]").live("blur", function() {
		var id = $(this).attr('id');
		var val = id.substr(id.length-1,id.length);
	 	var username = $(this).val();
 		var content = '';
		str = "info=1&username="+username;

		$('span.'+id).html('<img src="../../media/icons/ajaxLoader.gif">');
			
		$.ajax({  
			type: "GET",  
			url: "../../twitterlogin.php",  
			data: str,
			dataType: "json",  
			success: function(data) {  
			  $('span.'+id).hide();
			  $('#twitterInfo').hide();
			  if (data.name != '') { $("#foundersname"+val).val(data.name); }
			  if (data.url != '') { $("#founderswebsite"+val).val(data.url); }
			  // data.profile_image_url / data.location
			}
		});
	});

	// SEARCH TO BE CALLED EACH TIME SEARCH IS DONE
	
	$("#submitSearch").click(function() {
		searchCompanies();
	});

	$("#searchForm").submit(function() 
	  {
		return false; //not to post the form physically
	});

	$("#search_query").keyup(function() {
		searchCompanies();
	});

	if(typeof(company) != 'undefined') {
		$("#search_query").val(company);
		searchCompanies();
	}

	function searchCompanies() {

		var query = $("#search_query").val();

		$.getJSON("../../includes/findCompanies.php", { query:query , format: 'json'}, function(json){

			$("#msgSearch").html(json.results.length + ' results.');

			companies = json;

			// Create pagination element 
			$("#Pagination").pagination(json.results.length, {
					callback:pageselectCallback
			});
		});
	}
	
	

	/**
	* Callback function that displays the content.
	*
	* Gets called every time the user clicks on a pagination link.
	*
	* @param {int}page_index New Page index
	* @param {jQuery} jq the container with the pagination links as a jQuery object
	*/

	function pageselectCallback(page_index, jq){

		// Get number of elements per pagionation page from form
		var items_per_page = 10;
		var max_elem = Math.min((page_index+1) * items_per_page, companies.results.length);
		var newcontent = '';

		// Iterate through a selection of the content and build an HTML string
		for(var i=page_index*items_per_page;i<max_elem;i++) {
			// Main content
			newcontent += '<div class="listResult"> <a href="#" class="linkMoreResult">';
			newcontent += companies.results[i].name + '</a>';
			if (companies.results[i].nbroffounders != '') { 
				newcontent += ' - '; 
				for (j=1 ; j <= companies.results[i].nbroffounders ; j++) {
					newcontent += eval("companies.results["+i+"].founder"+j) + ', '; 
				}
			}
			// Remove last comma / Could also do a test in the for loop above to check for the last item of the list, but that's just more simple
			newcontent = newcontent.substring(0, newcontent.length-2);
			// Add the magnifier
			newcontent += '<a href="#" class="moreResults"><img src="../../media/icons/magnifier_zoom_in.png" id="iconMoreResult" align="right" border="0"></a>';
			newcontent += '</div>';
			// Subcontent
			newcontent += '<span class="subListResult">';

			newcontent += '<strong>'+companies.results[i].name+'</strong>: <a href="' + companies.results[i].address + '">visit the website</a><br /><br />';
			newcontent += '<strong>Service, product</strong>: ' + companies.results[i].service + '<br /><br />';
			newcontent += '<strong>Founders</strong>: <br>';
				for (j=1 ; j <= companies.results[i].nbroffounders ; j++) {
					newcontent += ' - '+ eval("companies.results["+i+"].founder"+j); 
					newcontent += ' (<a href="' + eval("companies.results["+i+"].founderwebsite"+j) + '">web</a> | '; 
					newcontent += '<a href="http://twitter.com/' + eval("companies.results["+i+"].foundertwitter"+j) + '">twitter</a>) </br>'; 
				}
			newcontent += '<br>' + companies.results[i].name + ' is located in ' + companies.results[i].location + ', ' + companies.results[i].zipcode + '</span>';
		}

		// Replace old content with new content
		$('#searchResult').html(newcontent);

		// Prevent click eventpropagation
		return false;
	}

	$("div.listResult").live("click", function(){
		$("span.subListResult").hide();
		$(this).next('span').toggle(); 
	});
	
	$("input, textarea").focus( function() {
			// only select if the text has not changed
			if(this.value == this.defaultValue) {
				this.select();
			}
	})
	
	$(function() {
		$.getJSON("../../includes/selectStage.php",{id: 1, ajax: 'true'}, function(j){
			var options = '';
			options += '<option value="0">Which stage are you in ?</option>';
			options += '<option value="00">- - - - - - - - - - - - - - - - - - - - - - -</option>';
	
			for (var i = 0; i < j.results.length; i++) {
				// alert(j.results[i].stageid);
				options += '<option value="' + j.results[i].stageid + '">' + j.results[i].name + '</option>';
			}
			$("select#stage").html(options);
		})
	})

	$("#topMenu").click(function(){
		window.location = "../../index.php"
	});

	$("div.others").hide();
	$("div.search").show();

	$("a.linkSearch").click(function(){
		$("div.others").hide("fast");
		$("div.search").show("fast");
		return false;
	});

	$("a.linkNew").click(function(){
		$("div.others").hide("fast");
		$("div.new").show("fast");
		return false;
	});

	$("a.linkLogin").click(function(){
		$("div.others").hide("fast");
		$("div.login").show("fast");
		return false;
	});

	$("a.linkAbout").click(function(){
		$("div.others").hide("fast");
		$("div.about").show("fast");
		return false;
	});

	// REGISTER / SAVE CODES 

		// CHECK if company exists
		$("#startupsname").blur(function() {

			//remove all the class add the messagebox classes and start fading
			$("#msgNewStartupsName").text('Checking...').fadeIn("slow");
			var startupsname = $(this).val();

			//check the username exists or not from ajax
			$.post("../../includes/findCompanies.php",{ startupsname:$(this).val() } ,function(data) 
			  {
				if(data == 'yes') { //if username not avaiable
					$("#msgNewStartupsName").fadeTo(200,0.1, function() //start fading the messagebox
					  {
						//add message and change the class of the box and start fading
						var msg = '<small><img src="../../media/icons/cancel.png"> Apparently, <strong>'+startupsname+'</strong> already exists in the directory ...</small>';
						$(this).html(msg).fadeTo(900,1);
					  });
				} else if (data == 'no') {
					$("#msgNewStartupsName").fadeTo(200,0.1,function()  //start fading the messagebox
					  {
						//add message and change the class of the box and start fading
						$(this).html('<img src="../../media/icons/tick.png">').fadeTo(900,1);
					  });
				}
			  });
		});

		function validateEmail(str) {
			var filter=/^.+@.+\..{2,3}$/
			if (filter.test(str)) {
				testresults = 'ok';
			} else {
				testresults = 'Please input a valid email address.';
			}
			
			return testresults;
		}

		$("#submitNew").click( function(event)
		{

			event.preventDefault();
			$('.msg').hide();
			var nbrFndrs = $("#numberOfFounders").val();
			var str = $("#new_startup").serialize();
			str += "&action=register&nbrFndrs="+nbrFndrs;

			//alert(str);
			
			$.ajax({  
				type: "POST",  
				url: "../../includes/saveNew.php",  
				data: str,  
				success: function() {  
					// We hide the form
					$("#formDiv").hide();
					//display message back to user here  
					// alert('succés!');
					$("#msgSubmitNew").show().css("display","block");
					$("#msgSubmitNew").css("background-color","#eee").fadeTo(200,0.1, function()  //start fading the messagebox
					  {
						//add message and change the class of the box and start fading
						$(this).html('Logging in.....').fadeTo(500,1, function()
						  {
							$content = 'Done! <br><br>';
							$content += '<a href="#" id="saveAnother">Click here to save another one<a>.';
							$(this).html($content);
						  });
					  });
		
				}
			});
			return false;  
		});

	$("#addFoundersLink").click(function(){
		var val = parseFloat($("#numberOfFounders").val())+1;
		$("#numberOfFounders").val(val);

		newcontent = '<table>';
		newcontent += '<tr><td>Twitter username (@...): </td><td><input name="founderstwitter'+val+'" type="text" id="founderstwitter'+val+'" value="" size="30" /> <span class="founderstwitter'+val+'"></span></td></tr>';
		newcontent += '<tr><td>Name:</td><td><input name="foundersname'+val+'" type="text" id="foundersname'+val+'" value="" size="30" /> </td></tr>';
		newcontent += '<tr><td>Website:</td><td><input name="founderswebsite'+val+'" type="text" id="founderswebsite'+val+'" value="http://" size="30" /> </td></tr>';
		newcontent += '</table>';
	
		$("#addFounders").append(newcontent);
		return false;
	});

	$("#saveAnother").live('click', function (){
		$("#msgSubmitNew").hide();
		$("#new_startup")[0].reset();
		$("#formDiv").show();
	})

});


//]]>

