$(window).load(function (){
	var print = function(){
        try{
		    if (console && console.log){
			    console.log.apply(console, arguments);
            }
		 }catch(error){};
	};

	function getFormInput(inputName){
		return $(":input[name=" + inputName + "]", $("form.new-hint-form"));
	}

	function setInputValue(inputName, value){
		$(getFormInput(inputName)).val( value);
		console.log(value,inputName);
	    console.log("agora do form:", $(getFormInput(inputName)).val());
	}
	/*
	* City selection
	*/
	var CitySelectButton = function (node){
		this.name = $(node).attr("href").substring(1);
		$(node).data("obj", this);         
		this.offImageURL = $("img", node).attr("src");
		this.onImageURL = this.offImageURL.replace("off", "on");
		this.image = $("img", node);
		this.selected = false;
	};

	CitySelectButton.prototype.select = function (){
		this.image.attr("src", this.onImageURL);
		this.selected = true;
		setInputValue("city", this.name);
	};

	CitySelectButton.prototype.deselect = function (){
		this.image.attr("src", this.offImageURL);
		this.selected = false;
	};

	CitySelectButton.prototype.toString = function(){
		return this.name;
	};


	/*
	* Caterogie selection
	*/
	var CategorieSelectButton = function (node){
		this.name = $("span", node).text();
		$(node).data("obj", this);         
		this.offImageURL = $("img", node).attr("src");
		this.onImageURL = this.offImageURL.replace("off", "on");
		this.image = $("img", node);
		this.selected = false;
	};

	CategorieSelectButton.prototype.select = function (){
		this.image.attr("src", this.onImageURL);
		this.selected = true;
		setInputValue("category", this.name.toLowerCase());
	};

	CategorieSelectButton.prototype.deselect = function (){
		this.image.attr("src", this.offImageURL);
		this.selected = false;
	};

	CategorieSelectButton.prototype.toString = function(){
		return this.name;
	};


	/* 
	* Reusable selection menu.
	* 
	*/
	var SelectMenu = function (nodes, newFunc, name){
		this.name = name;
		var obj = this;
		this.isValid = false;
		this.choices = nodes.map( function(){
			var c =  new newFunc($(this));
			$(this).click(function(){ 
				obj.onClicked($(this));
			});
			return c;
		});
	};

	SelectMenu.prototype.onClicked = function(node){
		var clicked = $(node).data("obj");
		this.choices.each(function(){
			if (this == clicked){
				this.select();
			} else{
				this.deselect();
			}
		});
		this.isValid = true;
		isFormPageValid(1);
	};

	var SmartField = function (node, min, max, validatorFunc, pageNum){

		var theObj = this;
		this.pageNum = pageNum;
		this.min = min;
		this.max = max;
		this.validatorFunc = validatorFunc || function(){return true};
		var parentNode = $(node).parents("tr");
		this.node = parentNode;
		this.input = $(":input", this.node);
		this.image = $("img", this.node);
		this.invalidImageURL = this.image.attr("src") || "";
		this.validImageURL = this.invalidImageURL.replace("error", "ok");
		$(node).data("obj", this);
		$(node).keydown(function(){
			theObj.validate(); 
		});
        this.valid=false;
		this.name = this.input.attr("name");
	};




	SmartField.prototype.validate = function(){
		var val = this.input.val() || "";
		var isValid = val.length > this.min && val.length < this.max && this.validatorFunc.apply(this,[ val]);
		var imageURL = this.validImageURL;
		if (!isValid){
			imageURL = this.invalidImageURL;
		}
        
		this.image.attr("src", imageURL);
		this.isValid = isValid;

		isFormPageValid(this.pageNum);
	};

	function onCancelClicked(){
	}

    function onReturnClicked(){
        $(".page3").hide();
        $(".page1").show();
    }
	function onMainSubmitClicked(){
		$(".page2").show();
		$(".page1").hide(); 
	}
    function categoryMouseHandler(e){

        var $el     = $(e.currentTarget);
        var type    = e.type;

        switch(type) {
            case 'mouseenter':
                    $('span', $el).show();
                break;
            case 'mouseleave':
                    $('span', $el).hide();
                break;
            
            default:
                // code
        }
    }

    function onFinalSubmitClicked(){
        // if 'empty' value for website form, null it:
        var website = getFormInput("website").val();
        if (website == "http://"){
            setInputValue("website", "");
        }
       var userEmail = $("input[name=user-email]", "#user-data-form").val();   
       var userName = $("input[name=user-name]", "#user-data-form").val();   
       setInputValue("user_name", userName);
        setInputValue("user_email", userEmail);
        
        $(".new-hint-form").submit();
        return false;
    }

    function onCreateHintReturned(data){
        if (data.success){
            track('/theride/home/dica/{city}/{category}/Enviou/Confirmado'.substitute({'city':$(getFormInput('city')).val(), 'category':$(getFormInput('category')).val()}));
            resetForm();
            text = "Sua dica foi enviada! Em breve ela será moderada, e você será avisado quando ela for pro ar."
            $(".page2").hide();
            $(".page3").show();
        }else{
            text = "Algo deu errado! Enquanto isso, pé na tábua.";// + data.errors[0]
            $(".message-minor", ".page2").text(text);
            $(".message", ".page2").text("");
            $("#user-data-form", ".page2").hide();
        }
        
    }
	function onImageChosen(){
        $("input[type=submit]", "#upload-hint-image-form").attr("disabled", "");
	}
    window.blu = resetForm;
    function resetForm(){

        categorieMenu.choices.each(function(){
        		this.deselect();
		});
        cityMenu.choices.each(function(){
        		this.deselect();
		});

        smartFields.each(function(e){
                e.input.val(e.name == 'website' ? 'http://' : "");
                e.validate();
        });

        $('.photo-preview-box img').attr('src', '#');
        $('.photo-preview-box .image-specs').css({display: 'block'});
	};





	           function onImageUploaded(data){
		       if(data.success){

			   $(":input[name=hash]", $("#crop_form")).val(data.data.hash);
			   

      		           $("img#cropbox").data("hash", data.data.hash); 
			   $(".page1").hide();
			   $("#photo-resizer").show();
			   // update datas
	                   var w = data.data.width;
		           var h = data.data.height;
		           var xStart = (300)/2;
		           var yStart = (200)/2;

                           
                           if (jCropAPI){
                               jCropAPI.destroy();
                               $("img#cropbox").unbind("load");
                           }
                          var options = {
			     onChange: showPreview,
			     onSelect: showPreview,
			     minSize: [300,200],
			     setSelect: [xStart,yStart, xStart + 300, yStart + 200],
			     aspectRatio: 1.5,
                             trueSize:[w,h]
		          };
                           $("img#cropbox").load(function(){
                                                     jCropAPI = $.Jcrop("#cropbox", options);;
                                                     
                           });
                           $("img#cropbox").attr("src", data.data.image); 
		           //$('#cropbox').get(0).src = data.data.image;
		       }else{
			   alert("error! " + data.errors);
		       }
	           }

	function onImageCropped(data){
		if(data.success){
			// update datas
			$("img", $(".photo-preview-box")).attr("src", data.data.image);       
            $(":input[name=image_hash]", ".new-hint-form").val(data.data.hash);
			$(".page1").show();
			$(".image-specs", $(".photo-preview-box")).hide();
			$("#photo-resizer").hide();
                        $.Jcrop("#cropbox").release();
                        //jcrop_api = $.Jcrop('#cropbox',options); 
		}else{
			alert("error! " + data.errors);
		}
	}


	function onCloseResizeImageWindow(){
		$(".page1").show();
		$("#photo-resizer").hide();

	}

	function showPreview(coords)
	{
        

		if (parseInt(coords.w) > 0)
		{
			// updates the valus on the form
			var form = jQuery("#crop_form");
			jQuery("input[name=x]", form).val(coords.x);
			jQuery("input[name=y]", form).val(coords.y);
			jQuery("input[name=x2]", form).val(coords.x2);
			jQuery("input[name=y2]", form).val(coords.y2);
		}
	}



	function enable(node, isEnabled, callback){
		if(isEnabled){
			node.click(callback);
		}else{
			node.unbind();
		}
		node.css("opacity", isEnabled? 1 : 0.3);             
	}

	var smartFields;
	var cityMenu;
	var categorieMenu;
	var smartFieldsPage2;
        var jCropAPI;
	function atachHandlers(){
		$("#photo-resizer").hide();
		$(".page2").hide();
		cityMenu = new SelectMenu($(".city-button"), CitySelectButton, "cityMenu");
		categorieMenu = new SelectMenu($(".categorie"), CategorieSelectButton, "categorieMenu");
        $(".categorie").bind('mouseenter mouseleave', categoryMouseHandler);
        $(".categorie span").hide();
		smartFields = jQuery.map( [
			["title", 2, 255],
			["address",8, 255],
			["website", 0, 512, isValidURL],
			["neighbourhood",3, 20],
			[ "description", 10, 1024]], function(obj, i){
				var input = getFormInput([obj[0]]);
				var fld = new SmartField(input, obj[1], obj[2], obj[3], 1);
				return fld;
			});
			smartFieldsPage2 = jQuery.map( [
				["user-name", 4, 31],
				["user-email", 6, 150, isValidEmail]], function(obj, i){

					var input = $("input[name="+obj[0]+"]", $("#user-data-form"));
					var fld = new SmartField(input, obj[1], obj[2], obj[3], 2);
					return fld;
				});
				$(".cancel-button", $("#new-hint")).click(onCancelClicked);
				$(".send-another", $("#new-hint")).click(onReturnClicked);


				$("#upload-hint-image-form").ajaxForm({"success":onImageUploaded, 'dataType':"json"});
				$(":input[type=reset]", $("#crop_form")).click(onCloseResizeImageWindow);
				$("#crop_form").ajaxForm({"success":onImageCropped, 'dataType':"json"});
				$(".new-hint-form").ajaxForm({"success":onCreateHintReturned, 'dataType':"json"});
				enable($(".submit-button", $("#new-hint")), false);
				enable($(".submit-final-page-button", $("#new-hint")), false);
        $("input[type=file]", "#upload-hint-image-form").change(onImageChosen);
                $("input[type=submit]", "#upload-hint-image-form").attr("disabled", "disabled");
                isFormPageValid(1);
                isFormPageValid(2);
			}

			function isFormPageValid(pageNum){
                var valid = true;
				if (pageNum==1){
					var buttonNode= $(".submit-button", $("#new-hint"));
                    var callback = onMainSubmitClicked;
					var toCheck = [ cityMenu, categorieMenu].concat(smartFields);
				}else if(pageNum==2){
					var buttonNode= $(".submit-final-page-button", $("#new-hint"));
					var toCheck = smartFieldsPage2;
                    var callback= onFinalSubmitClicked;
				}
				jQuery.each(toCheck, function(i,o){
		            if (!o.isValid) {
                        valid = false;
						return false;
					}
		        });
                if(valid){
					enable(buttonNode, true, callback);
                }else{
                    enable(buttonNode, false);
                }
			}
			window.isFormPageValid = isFormPageValid;
                  
			atachHandlers();

 	function isValidURL(value){
        // we allow empty or default values
        if (value == "" || value == "http://") return true;
		var re =  /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
		return re.test(value) || re.test("http://"+value);        
	}

	function isValidEmail(value){
		var re = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/;
		return re.test(value) ;
	}

		});
