/**
 *
 * @package    Worketer
 * @subpackage Application/JS
 * @author     Simon Lamellière
 * @author	   Worketer SARL
 * @static		JS_STATIC
 */

jQuery(document).ready(function() {

	jQuery.fn.exists = function(){ return jQuery(this).length>0; }

	$(".worketer_text_dynamic").each(function(){
		$(this).attr("default", $(this).val());
		prototype = function(){ $(this).removeClass("disabled"); if($(this).attr("default") == $(this).val()) $(this).val("") };
		prototypeB = function(){ if(jQuery.trim($(this).val()) == "") { $(this).val($(this).attr("default")); $(this).addClass("disabled"); } };
		$(this).addClass("disabled").click(prototype).focus(prototype).blur(prototypeB);
	});
	
	$.fn.saveEcho = function()
	{
		if($("#changes").val() == "1")
			return confirm("Les modifications ne sont pas enregistrées, voulez-vous continuer?") ? true : false;
	};

	
	if($('#hash-tag').exists() && window.location.hash)
	{
		$(".to_see").show();
		$('#hash-tag').val(window.location.hash);
	}
	
	$(".open-trigger-tipsy").tipsy({ title: 'alt', live: true, gravity: 's' });
		
	$.fn.reloadChart = function(id, stype)
	{
		var so = new SWFObject("/stOfcPlugin/images/open-flash-chart.swf", "chart", "851", "250", "9", "#FFFFFF");
		so.addVariable("data", escape("/default/graph?id="+id+"&type="+stype));
		so.addParam("allowScriptAccess", "sameDomain");
		so.write("flashcontent");	
	};
	
	$(".bind-skill-chart li").live("click", function()
	{
		$(".bind-skill-chart li").removeClass("active");
		$(this).addClass("active");
		$.fn.reloadChart($("a", this).attr("id"), $("a", this).attr("name"));
		$.scrollTo($("body"), 500);
	});
	
	if($(".bind-skill-chart li.first_of").exists())
		$(".bind-skill-chart li.first_of").click();
	
	/* corners */
	if(typeof $.fn.corner == "function")
	{
		$(".corner").corner("8px");
		$(".icon-activity").corner("2px");
		$(".corner16").corner("16px");
		$(".corner4").corner("4px");
		$(".captcha").corner("4px");
		$("#loading-overlay, #loading-overlay-error").corner("6px");
		$("#loading-overlay, #loading-overlay-error").hide();
		$("ul.menu li p").corner("16px");
	}
	
	/* forms*/
	$("span.ok").prev().addClass("correct");
	$("span.error").prev().addClass("invalid");
	$("span.error:first").prev().focus();

	$("#subscribe_env").hide();
	
	$.fn.sichange = function()
	{
		var gid = $("#situation_id").val();
		
		if(gid == 2 || gid == 5 || gid == 7 || gid == 8 || gid == 6)
			$("#subscribe_env").hide();
		else
			$("#subscribe_env").show();
	};
	
	if($("#situation_id").exists())
	{
		$.fn.sichange();
		$("#situation_id").change(function() { $.fn.sichange(); });
	}
	
	$(function() {
		$( "#slider-range-company" ).slider({
			range: true,
			min: 0,
			max: 1000,
			step: 50,

			values: [ $("#company_size_min").val(), $("#company_size_max").val() ],
			slide: function( event, ui ) {
				$( "#amount" ).val( ui.values[ 0 ] + " - " + ui.values[ 1 ] + (ui.values[ 1 ]  == 1000 ? "+" : '') + "" );
				$("#company_size_min").val(ui.values[0]);
				$("#company_size_max").val(ui.values[1]);
			}
		});
		$( "#amount" ).val( $( "#slider-range-company" ).slider( "values", 0 ) +
			" - " + $( "#slider-range-company" ).slider( "values", 1 ) + ($( "#slider-range-company" ).slider( "values", 1 ) == 1000 ? "+" : '') + "" );
	});

	$( "#city" ).autocomplete({
			source: function( request, response ) {
				$.ajax({
					url: "/google/geocode/json",
					dataType: "json",
					data: {
						address: request.term,
						sensor: false
					},
					success: function( data ) {
						response( $.map( data.results, function( item )
						{
							var country = null;
							var zip = null;
							var city = "";
							var street = null;
							var number = null;
							var state = null;

							for(i in item.address_components)
							{
								if(item.address_components[i].types[0] == "administrative_area_level_1")
									state = item.address_components[i].long_name;
								if(item.address_components[i].types[0] == "country")
									country = item.address_components[i].short_name;
								if(item.address_components[i].types[0] == "locality")
									city = item.address_components[i].long_name;
								if(item.address_components[i].types[0] == "postal_code")
									zip = item.address_components[i].long_name;
								if(item.address_components[i].types[0] == "street_number")
									number = item.address_components[i].long_name;
								if(item.address_components[i].types[0] == "route")
									street = item.address_components[i].long_name;
							}

							return {
								label: city + (zip ? " (" + zip +")": "")  + (state ? ", " + state : "")  + (country ? ", " + country : ""),
								value: city,
								country: country,
								street: street,
								number: number,
								city: city,
								zip: zip,
								coordinates: item.geometry.location.lat + "," + item.geometry.location.lng
							}
						}));
					}
				});
			},
			select: function(event, ui)
			{
				if(ui.item.zip != null)
					$("#zip").val(ui.item.zip);
				
				if(ui.item.country != null)
					$("#country_code").val(ui.item.country);
			},
			minLength: 2
		});
	
	$(function() {
		$( "#slider-range-wage" ).slider({
			min: 15,
			max: 200,
			step: 1,

			values: [ $("#wage_size_min").val() ],
			slide: function( event, ui ) {
				$( "#amount-wage" ).val( ui.values[ 0 ] + "k");
				// + ui.values[ 1 ] + "k" 
				$("#wage_size_min").val(ui.values[0]);
				//$("#wage_size_max").val(ui.values[1]);
			}
		});
		
		$( "#amount-wage" ).val( $( "#slider-range-wage" ).slider( "values", 0 ) + "k" );
			// +
			//"k - " + $( "#slider-range-wage" ).slider( "values", 1 ) + "k" );
	});
	
	$.fn.experienceAdded = function(el, title)
	{
		el.addClass("valid").removeClass("invalid").html(title + " : okay ;-)");
	};
	
	$.fn.addExperience = function(first)
	{
		var aid = $(".experience", ".experiences").length + 1;

		$.ajax({
			url: '/experience/index',
			type: 'GET',
			data: { id: aid },
			success: function(val)
			{
				if(first == true) $(".experiences").html("");
				$(".experiences").append(val);
				$.scrollTo( $("#experience_"+aid), 500 );
				$(".ui-layout-center").scrollTo( $("#experience_"+aid), 500 );
			}
		});
	};
	
	// 2 et 5
	if(typeof $("input[type='checkbox'].worketer_input_toggle").checkToggle == "function")
	$("input[type='checkbox'].worketer_input_toggle").checkToggle();
	
	// Username
	if($("#username").exists())
		$("#username").click().focus();
	
	/*
	* jQuery UI Autocomplete Select First Extension
	*
	* Copyright 2010, Scott González (http://scottgonzalez.com)
	* Dual licensed under the MIT or GPL Version 2 licenses.
	*
	* http://github.com/scottgonzalez/jquery-ui-extensions
	*
	* patch by Simon Lamelliere
	*/
	(function( $ ) {
	
		$(".ui-autocomplete-input").live( "autocompleteopen", function()
		{
			var autocomplete = $( this ).data( "autocomplete" ),
			menu = autocomplete.menu;
	
			if ( !autocomplete.options.selectFirst ) {
				return;
			}
	
			$(".ui-autocomplete-input").bind('keyup', function(e)
			{
				$(".ui-autocomplete-input").unbind('keyup');
	
				if(e.which == 13 && $('.ui-state-hover').height() == null)
				{
					menu.activate( $.Event({ type: "mouseenter" }), menu.element.children().first() );
					menu.select( $.Event({ type: "mouseenter" }), menu.element.children().first() );
				}
			});
	
		});
	
	}( jQuery ));
}); 
