if (typeof (T3) == "undefined") T3 = {};

T3.RegisterNamespace = function (namespace) {
    /// <summary>Registers a new namespace</summary>
    /// <param name="namespace" type="string">The namespace to register.</param>

    var root = window;
    var parts = namespace.split('.');
    for (var i = 0; i < parts.length; i++) {
        var part = parts[i];
        var ns = root[part];
        if (!ns) {
            ns = root[part] = {};
        }
        root = ns;
    }
};

T3.Init = function(){
	new function () {
        $(function () { initialize(); });
    };

	var currentCategory = $('#navigation > ul > li.current');
    var currentPage = $('#navigation > ul > li > ul > li.current');
    
	function initialize() {
		$('#navigation > ul > li')
			.mouseenter(function() {
				$(this).addClass('hover');
				currentCategory.removeClass('current');
			})
			.mouseleave(function() {
				$(this).removeClass('hover');
				currentCategory.addClass('current');
			});
	}
}

T3.Contact = function (elm) {
    var _this = this;
    var _elm = elm;

    new function () {
        $(window).unload(function () { dispose(); });
        $(function () { initialize(); });
    };

    function dispose() {
        _this = null;
    };

    function initialize() {
        $(_elm).validate({
            errorPlacement: function (error, element) { console.log("ERROR"); return true; },
            rules: {
                first_name: { required: true },
                last_name: { required: true },
                email: { required: true, email: true },
                description: { required: true }
            },
            submitHandler:submit
        });

    }

    function submit(form) {
        $.ajax({
            type: "POST",
            dataType: "jsonp",
            url: "https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8",
            data: $(form).serialize(),
            success: function (data, status) {
                $("div#contact-box").html("Your message has been sent. Thank you!");
            },
            error: function (error) {
                // sales force returns an error even though it actually sends the message succesfully.
                $("div#contact-box").html("Your message has been sent. Thank you!");
            }
        });

        //fld_1_fn
        //fld_1_ln
        //fld_1_em
        //fld_3_title
        //fld_21 - phone
        //fld_22 - phone
        //fld_4 - desc

        // Post data to CRM tool as well
        $.ajax({
            type: "POST",
            dataType: "jsonp",
            url: "http://cloud.tier3.com/acton/forms/userSubmit.jsp",
            data:{
                fld_1_fn: $("#first_name").val(),
                fld_1_ln: $("#last_name").val(),
                fld_3_title: $("#title").val(),
                fld_1_em: $("#email").val(),
                fld_21: $("#phone").val(),
                fld_22: $("#phone").val(),
                fld_4: $("#description").val()
            },
            success: function (data, status) {
                
            },
            error: function (error) { 
            }
        });
    }
}

// Home Feed
T3.TwitterFeed = function(elm){
	var _this = this;
	var _elm = elm;
	var _data;
	var _index = 0;
	var _current;
	var _previous;
	var _month = [ "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEPT", "OCT", "NOV", "DEC" ];
	
	new function () {
        $(window).unload(function () { dispose(); });
        $(function () { initialize(); });
    };

    function dispose() {
        _this = null;
		_data = null;
    };

    function initialize() {
		T3.Utilities.GetTweets(initTweets);
	}
	
	function initTweets(data, textStatus, XMLHttpRequest) {
		_data = data;
		
		buildNavigation();
		display();
	}
	
	function display(dir) {
		var d = _data[_index];
		
		if(dir == null) dir = 1;
		
		_previous = _current;
		_current = T3.Utilities.CreateElement(_elm,"div","tweet_" + _index,"absolute-elm tweets");
		
		var date = T3.Utilities.ParseDate(d.created_at);
		
		_current.append("<a class=\"author\" href=\"#\">@tier3</a>");
		_current.append(d.text);
		_current.append("<span class=\"date\">" + _month[ date.getMonth() ] + " " + date.getDate() + "</span>");
		
		$(_current).link();

		_current.css("z-index",1);
		_current.css("left",$(elm).outerWidth() * dir);
		_current.animate( { left:0 },{ queue:false, duration:"1000", easing: "easeOutCirc" } );
		if(_previous) _previous.animate( { left:-$(elm).outerWidth() * dir },{ queue:false, duration:"1000", easing: "easeOutCirc", complete:function() { _previous.remove(); } } );
	}
	
	function buildNavigation(){
		var left = T3.Utilities.CreateElement(_elm,"div","tweet_nav_left","absolute-elm");
		var spacing = 10;
		
		$.imgpreload("images/buttons/arrow_left.png", function() {			
			left.css("cursor","pointer");
			left.css("z-index",999);
			left.css("opacity",.2);
			left.append(this);
			
			$(this).attr("width", 16);
			$(this).attr("height", 14);
			
			var l = 0;
			
			left.css("top",Math.round( $(_elm).outerHeight()/2 - left.outerHeight()/2 ));
			left.css("left",l);
			
			left.click( function() {	
				_index--;
				
				if(_index < 0) _index = _data.length - 1;
				display(-1);
			});
			
			left.mouseover( function() {
				//$(this).animate( { left:l - spacing, opacity:.5 },{ queue:false, duration:"1000", easing: "easeOutCirc" } );
			});
			
			left.mouseout( function() {
				//$(this).animate( { left:l, opacity:.2 },{ queue:false, duration:"1000", easing: "easeOutCirc" } );
			});
		});
		
		var right = T3.Utilities.CreateElement(_elm,"div","tweet_nav_right","absolute-elm");
		
		$.imgpreload("images/buttons/arrow_right.png", function() {			
			right.css("cursor","pointer");
			right.css("z-index",999);
			right.css("opacity",.2);
			right.append(this);
			
			$(this).attr("width", 16);
			$(this).attr("height", 14);
			
			var l = $(_elm).outerWidth() - right.outerWidth();
			
			right.css("top",Math.round( $(_elm).outerHeight()/2 - right.outerHeight()/2 ));
			right.css("left",l);
			
			right.click( function() {
				_index++;
				
				if(_index > _data.length - 1) _index = 0;
				display();
			});
			
			right.mouseover( function() {
				//$(this).animate( { left:l + spacing, opacity:.5 },{ queue:false, duration:"1000", easing: "easeOutCirc" } );
			});
			
			right.mouseout( function() {
				//$(this).animate( { left:l, opacity:.2 },{ queue:false, duration:"1000", easing: "easeOutCirc" } );
			});
		});
	}
}



// Blog Feed
T3.BlogTwitterFeed = function(elm, count){
	var _this = this;
	var _elm = elm;
	var _data;
	var _count = (count) ? count : 5;
	var _index = 0;
	
	new function () {
        $(window).unload(function () { dispose(); });
        $(function () { initialize(); });
    };

    function dispose() {
        _this = null;
		_data = null;
    };

    function initialize() {
		T3.Utilities.GetTweets(initTweets);
	}
	
	function initTweets(data, textStatus, XMLHttpRequest) {
		_data = data;
		
		display();
	}
	
	function display() {
		for( var i = 0; i < _count; i++ ){
			var li = T3.Utilities.CreateElement(_elm, "li");
			li.html(_data[i].text);
			li.link();
		}
	}
}

jQuery.validator.addMethod("phoneUS", function (value, element) {
    value = value.replace(/\s+/g, "");
    return this.optional(element) || value.length > 9 &&
		value.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
