/**
 * @author Stephen Rhyne
 */
//template engine
(function(){
  var cache = {};
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :

      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();

(function(GLOBAL){
	var url, login;
	
	//check session. if UID is "" then send user to login else save UID to window.data for user later
	url = "../main/index.php/Login/showSession";
	login = "../";
	
	function showModal(el){
		var w, wHeight, wWidth, cWidth, cHeight, _screen;
		
		
		w = $(window);
		wHeight = w.height();
	   	wWidth = w.width();
	   	cWidth = wWidth * .5; 
	   	cHeight = wHeight * .5; 

		_screen = $("#modal-screen");
		_screen[0] && _screen.remove();
		
	   	_screen = $("<div/>",{
				id : "modal-screen",
				click : function(){
					$(this).remove();
				}
			}).appendTo("body");
			
		el.css({
			top : (wHeight - cHeight)/2, 
			left : (wWidth - cWidth)/2,
			width : cWidth,
			height : cHeight
		}).appendTo(_screen).fadeIn(500);
		
	};
	
	function check(){
		return $.getJSON(url, function(r){
				var user, valid, data;
				
				user = r.current_user;
				valid = user.uid;
				data = {};
				
				if(valid === ""){
					return window.location.href = login;				
				}
				return $.data(window,user);
        });
	}
	
	function checkPayment(){
		var data, el;
		
		data = $.extend({}, $.data(window));
		 
		//if owner status is 0 then you are good!
		if(data.owner_status === '0'){
			return true;
		}
		
		el = $("<div/>",{
			id : 'cancel-notice', 
			html : 	tmpl("cancel_notice_tmpl", data)
		});
		
		showModal(el);	
		window.scrollTo(0,0);
		PDI.group.resetGroupPosition && PDI.group.resetGroupPosition();
		//return false if you want to limit features
		return false;
	};
	
	function checkProfile(){
		var email = $.data(window,"email"),
			last_updated_time = $.data(window,"last_updated_time").split(" "),
			date_arr = last_updated_time[0].split("-"),
			year = parseFloat(date_arr[0]),
			month = parseFloat(date_arr[1]-1),
			day = parseFloat(date_arr[2]),
 			d = new Date(year,month,day),
			pass_date_str = d.toString(),
			url = "../account/accounttab.htm";
		if(pass_date_str != "Invalid Date")
		{
			var today = new Date(),
				one_day=1000*60*60*24,
				pass_days = Math.ceil((today.getTime()-d.getTime()) /(one_day));
		}
		if(!email || pass_date_str == "Invalid Date" || pass_days > 90){
			if(!email){
				alert("We really need your email address. We are going to direct you to the Account tab where you can update your profile.\n\n"+
					 "Put all that good stuff in Ok!\n\nNOTE: If you update your profile and you still get this message just login again.");
			}
			if(pass_date_str == "Invalid Date"){
				alert("We need you to set your password for webPDI. We are going to direct you to the Account tab. Click on on \"Updated webPDI Password\"."+
				"\n\nNOTE: If you update your profile and you still get this message just login again.");
			}
			if(pass_days > 90){
				alert("We need you to update your password for webPDI. I know, it's annoying but we gotta do it once every 90 days."+
				"\n\nNOTE: If you update your profile and you still get this message just login again.");
				url += "#password";
			}
			location.href = url;
		}
	}
	
	GLOBAL.session = {
		check : check, 
		checkPayment : checkPayment, 
		checkProfile : checkProfile
	};
	
})(window);



//stevo box center alert msg on screen
$.fn.reposition = function(){
	var _window = $(window),
		window_offset = _window.scrollTop(),
		window_width = _window.width(),
		modal_width = this.width(),
		modalLeftMargin = ((window_width - modal_width) / 2);
		
	this
		.css({
			top : window_offset+30+"px",
			left : modalLeftMargin+"px"
		})
		.show(300);
};
//detect browser and save browser object to window for later use. 
//if user is using the crap that is MSIE then they are alerted and sent to chrome download page. 
var browser = {
    saveBrowser: function(){
		$.data(window,"testing","test");
        var userAgent = navigator.userAgent.toLowerCase();
        jQuery.browser = {
            version: (userAgent.match(/.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/) || [])[1],
            chrome: /chrome/.test(userAgent),
            safari: /webkit/.test(userAgent) && !/chrome/.test(userAgent),
            opera: /opera/.test(userAgent),
            msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
            mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent),
			iphone : /iphone/.test(userAgent),
			ipad : /ipad/.test(userAgent)	
        };
		if($.browser.iphone == true){
			window.location = "pdiphone/login.html";
		}
        $.each(jQuery.browser, function(i){
            if (this == true) 
			{
				return $.browser.real = i+"_"+$.browser.version;
			}			
        });
    },
    avoidIE: function(){
       var msieHtml = "<div id=\"msie\"><img src=\"images/idestroyerjp.jpg\" alt=\"IE SUCKS!\"/><p>WebPDI " +
        	"does not support the use of the Microsoft Internet Explorer browser. It's extremely slow, " +
        	"non-compliant with standards, and full of bugs. <b>It's just garbage</b>. For a rich, reliable WebPDI " +
        	"experience use Google Chrome. <b>We are directing you to the Chrome download website right now." +
        	"Chrome is available for PC's, MAC's, and Linux machines</b></p></div>",
			using_msie = $.browser.msie;
        if (using_msie) {
			$(msieHtml).appendTo("body").reposition();
            window.setTimeout(function(){
                location.href = "http://www.google.com/chrome?hl=en";
            }, 10000)
        }
    }
}
//nav global jQuery for all nav pages. 
$.fn.setNav = function(){
	var self = this;
	self
		.delegate("a.help","click",function(){
			var data = $.data(window);
			$.extend(Zenbox._settings,{
					requester_email : data.email,//data.email,
					requester_name : data.username,
					request_description:"*** For us :).. UID: "+data.uid+", Browser: "+$.browser.real+" ***",
					request_subject: ""
				});
	        Zenbox.show();
	        return false;
		});
}
var twitter = {
	url : "http://api.twitter.com/1/statuses/user_timeline/webpdi.json?callback=?",
	get : function(callback){
		var url = this.url;
		var thisObj = this;
		$.getJSON(url,function(data){
			callback.call(thisObj,data);
		});
	},
	replaceURLWithHTMLLinks : function(text) {
	  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	  return text.replace(exp,"<a href='$1'>$1</a>"); 
	},
	getLastUpdate : function(){
		this.get(function(data){
			var lastTweet = data[0].text,			
				tweetTypes = {
					news : lastTweet.indexOf("#news"),
					issue : lastTweet.indexOf("#issue")
				};
			lastTweet = this.replaceURLWithHTMLLinks(lastTweet);		
			if(tweetTypes.news >= 0)
			{
				lastTweet = "<img src=\"images/news_48.png\" class=\"news\" alt=\"News\"/><p>&#8220;" + lastTweet.replace("#news","");
			}
			else if(tweetTypes.issue >= 0)
			{
				lastTweet = "<img src=\"images/warning_48.png\" class=\"issue\" alt=\"Warning\"/><p>&#8220;" + lastTweet.replace("#issue","");
			}
			else{
				lastTweet = "<p>&#8220;"+lastTweet;
			}
			var twitter_link = "<a class=\"follow_us\" target=\"_blank\" href=\"http://www.facebook.com/pages/webPDI/112357688774733\">@facebook</a></p>";
			$("#twitter").hide().html(lastTweet+"&#8221;"+twitter_link).fadeIn(1000);
		});		
	}	
	//end of get
};

String.prototype.parseHashTag = function(attr_str,href){
	return this.replace(/[#]+[A-Za-z0-9-_:]+/g, function(tag) {
		return "<a "+attr_str+" href='"+href+tag+"' title='Records Tagged with "+tag+"'>"+tag+"</a>";
	});
};

String.prototype.parseTime = function(attr_str,href){
	return this.replace(/[@]+[A-Za-z0-9-_:]+/g, function(tag) {
		return "<a "+attr_str+" href='"+href+tag+"' title='Records happening "+tag+"'>"+tag+"</a>";
	});
};














