var not_iphone = ((!navigator.userAgent.match(/iPhone/i)) && (!navigator.userAgent.match(/iPod/i)));
var home = {
    init: function() {
		if(not_iphone){
			home.capas.init();
			home.twitter.init();
		}else{
			$('.wtf h1').html('Escolha o seu');
			$('.wtf li a').attr('href','#');
		}
		home.contato.init();
		home.lang.init();
    },
	
	lang: {
		init: function(){
			$('.lang a').click(function(){
				$.cookie("lang", $(this).attr('class'), { expires: 365 });
				window.location = window.location;
			});
		}
	},

	capas: {
		init: function(){
			$('.wtf').hover(function(){
				$('.wtf h1').fadeIn();
			},function(){
				$('.wtf h1').fadeOut();				
			});
			$('.wtf li').hover(function(){
				$(this).addClass('hover');
			},function(){
				$(this).removeClass('hover');			
			});
			// home.capas.make_scrollable(".wtf .scrollable", ".wtf ul");
			home.capas.jcarousel(".wtf ul");
		},
		
		make_scrollable: function(wrapper, scrollable){
			var wrapper = $(wrapper), scrollable = $(scrollable);
			scrollable.hide();
			var interval = setInterval(function(){
			var images = scrollable.find('img');
			var completed = 0;
			images.each(function(){
				if (this.complete) completed++;
			});
			if (completed == images.length){
				clearInterval(interval);
				setTimeout(function(){
					wrapper.css({overflow: 'hidden'});
					scrollable.slideDown('slow', function(){
						home.capas.enable(wrapper, scrollable);
					});
				}, 10);
			}
			}, 10);
		},
		
		enable: function(wrapper, scrollable){
			var inactiveMargin = 0;
			var wrapperWidth = wrapper.width();
			var wrapperHeight = wrapper.height();
			var scrollableHeight = scrollable.outerHeight() + 2*inactiveMargin;
			wrapper.mousemove(function(e){
				var wrapperOffset = wrapper.offset();
				var top = (e.pageY -  wrapperOffset.top) * (scrollableHeight - wrapperHeight) / wrapperHeight  - inactiveMargin;
				if (top < 0){
					top = 0;
				}
				wrapper.scrollTop(top);
			});
		},
		
		jcarousel: function(wrapper){
			$(wrapper).jcarousel({
		        vertical: true,
		        scroll: 1,
				auto: 3,
				wrap: 'circular'
		    });
		}
	},

    twitter: {
		page: 1,
		init: function() {
//			var url = "http://twitter.com/status/user_timeline/euro4dbrasil.json?count=9&page="+home.twitter.page+"&callback=?";
	        var url = "twitter.php?count=10&page="+home.twitter.page+"&callback=?";
			home.twitter.show_tweets(url);
		},
		show_tweets: function(url){
		    $(".twitter ul").html('');
			$.getJSON(url, function(data) {					
				$.each(data, function(i, item) {
					$(".twitter ul").append("<li>" + home.twitter.linkify(item.text) + "</li>");
	            });
        	});
			$(".twitter").append('<p class="mais" id="mais'+home.twitter.page+'"><a href="javascript:">Mais</a></p>');
			
			$('.twitter #mais'+home.twitter.page+' a').bind('click',function(){
				home.twitter.page++;
				$('.twitter #mais'+(home.twitter.page-1)+' a').hide();
				home.twitter.init();
			});
		},
		linkify: function(text) {
		    if (text) {
		        text = text.replace(
		            /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
		            function(url){
		                var full_url = url;
		                if (!full_url.match('^https?:\/\/')) {
		                    full_url = 'http://' + full_url;
		                }
		                return '<a href="' + full_url + '" target="_blank">' + url + '</a>';
		            }
		        );
		    }
		    return text;
		}
    },

    contato: {
        init: function() { 
			home.contato.botoes();
	           
            jQuery.extend(jQuery.validator.messages, {
                required: "Campo obrigatório.",
                email: "Digite um email válido.",
                minlength: "Deve ter no mínimo {0} caracteres."
            });
            home.contato.validar();
        },

		botoes: function(){
			if(not_iphone){
				$('.link-contact a').click(function(){
					$('.contact').animate({height:'400px', top:'690px'});
				});
				$('.contact .fechar a').click(function(){
					$('.contact').animate({height:'0px', top:'1090px'}, function(){
						$(this).hide();
					});
				});
			}else{
				$('.link-contact a').click(function(){
					$('.contact').animate({height:'470px', top:'1065px'});
				});
				$('.contact .fechar a').click(function(){
					$('.contact').animate({height:'0px', top:'1500px'}, function(){
						$(this).hide();
					});
				});
			}	
		},

        validar: function() {
            var Locked = false;
            $('#frmContact').validate({

                submitHandler: function() {
                    if (Locked === true) {
                        return;
                    }
                    Locked = true;
                    $.ajax({
                        type: "POST",
                        url: "email.php",
                        data: "nome=" + $('#nome').val() +
                              "&email=" + $('#email').val() +
                              "&ddd=" + $('#ddd').val() +
                              "&tel=" + $('#tel').val() +
                              "&mensagem=" + $('#mensagem').val(),
                        dataType: "json",
                        success: function(result) {
                            Locked = false;
                            if (result == 1) {
                                $('#frmContact fieldset').prepend('<label class="success">Mensagem enviada com sucesso.</label>');
								window.setTimeout("$('#frmContact fieldset label.success').fadeOut()",1000);
                            } else {
                                $('#frmContact fieldset').prepend('<label class="error">Ocorreu um erro no envio. Tente novamente mais tarde.</label>');
                            }
                        }
                    });
                },

                rules: {
                    nome: "required",
                    email: {
                        required: true,
                        email: true
                    },
                    mensagem: "required"
                }
            });
        }
    }
}

$(document).ready(function() {
	home.init();
});


// linkify
(function($){

  var url1 = /(^|&lt;|\s)(www\..+?\..+?)(\s|&gt;|$)/g,
      url2 = /(^|&lt;|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|&gt;|$)/g,

      linkifyThis = function () {
        var childNodes = this.childNodes,
            i = childNodes.length;
        while(i--)
        {
          var n = childNodes[i];
          if (n.nodeType == 3) {
            var html = $.trim(n.nodeValue);
            if (html)
            {
              html = html.replace(/&/g, '&amp;')
                         .replace(/</g, '&lt;')
                         .replace(/>/g, '&gt;')
                         .replace(url1, '$1<a href="http://$2">$2</a>$3')
                         .replace(url2, '$1<a href="$2">$2</a>$5');
              $(n).after(html).remove();
            }
          }
          else if (n.nodeType == 1  &&  !/^(a|button|textarea)$/i.test(n.tagName)) {
            linkifyThis.call(n);
          }
        }
      };

  $.fn.linkify = function () {
    return this.each(linkifyThis);
  };

})(jQuery);

//cookie
jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


