
$(function(){
	
	$("#phatbox-header > a").click(function(event){
		event.preventDefault(); event.stopPropagation();
		RentPost.UI.closeLightBox();
	});	
	
	
	// basic error handler (and denying of cache for IE issues)
	$.ajaxSetup({
		XMLHttpRequest: function(XMLHttpRequest){
			RentPost.UI.setLoadingCursour();
		},
		complete: function (){
			RentPost.UI.removeLoadingCursour();
		},
		error : function(XMLHttpRequest,textStatus, errorThrown) {
			var notice = '';
			// make sure we're getting the final state, need to avoid "aborted" and whatever else
			if(XMLHttpRequest.readyState == 4) {
				//check all of our statuses and report
				if(XMLHttpRequest.status==0){
					notice = 'You are offline!!\n Please Check Your Network.';
				} else if(XMLHttpRequest.status==404){
					notice ='Requested URL not found.';
				} else if(XMLHttpRequest.status==500){
					notice ='We have encountered an error processing your request.\nWe have logged it and will be taking action promptly.';
				} else if(XMLHttpRequest.status == 401){
					RentPost.Utils.sessonTimeOut();
					return;
				} else if(errorThrown=='parsererror'){
					notice = 'Error.\nParsing JSON Request failed.';
				} else if(errorThrown=='timeout'){
					notice = 'Request Time out.';
				} else {
					return;
				}
			} else {
				return;
			}
		
			//use showNotice if we have it avail (make sure we have the notice here too)
			if(typeof showNotice == 'function' && $("div.notice-thingy").length){
				showNotice(notice,true);
			} else {
				alert(notice);
			}
			
			log(XMLHttpRequest);
			log(textStatus);
			log(errorThrown);
		}
	});
	
	
	// :: footer ::
    /*we're using zendesk now
	$("#help-me").click(function(event){
		event.preventDefault();

		if($("#help").length){
			$("#help").trigger("click");
		} else {
			openLightBox(this.href,"Help");
		}
	});
	*/
	
	$("#tac").click(function(event){
		event.preventDefault();
		openLightBox(this.href,"Terms and Conditions");
	});
	
	$("#privacy").click(function(event){
		event.preventDefault();
		openLightBox(this.href,"Privacy Policy");
	});
	
	// :: footer :: end
	
});


//------
//
//   LightBoxes & Notices
//
//------

(function(jQuery){
var lightboxRequest,
 openLightBox = function(url,title,callBackFunction,titleMenu,forceTitleFormatting){
	var phatboxWrapperEl = $("#phatbox-wrapper").undelegate(); //clear any evt handlers too
	
	// cleanup
	$("#phatbox-body").empty().removeAttr("style");
	if(lightboxRequest)
		lightboxRequest.abort();

	phatboxWrapperEl.css("display","block");

	//format title:
	if(forceTitleFormatting)
		title = title.capitalize();
	
	//title menu is for add/remove/edit functionality
	if(titleMenu){
		title = title+ " " +titleMenu;
	}
	
	//setup phatbox while they wait
	$("#phatbox-header h1").html("Loading...");
	$("#phatbox").css("width","400px");
	
	lightboxRequest = $.get(url, function(data) {
		
						//was this aborted?
						if(lightboxRequest.status != 200)
							return;
						
						$("#phatbox-header h1").html(title.replace("&Amp;","&"));
						$("#phatbox").removeAttr("style"); // removes about 500px width
						$("#phatbox-body").html(data);
	
						
						var phatboxDataEl = phatboxWrapperEl.find("div.phatbox-data");
							//phatboxHeightFix = phatboxDataEl.find("div.height-fix"); //height-fix hack

						// resizing max height depending on browser height
						var minPhatboxSpacing = 100,
							offsetDividend = 1.2,  // say top: 50; was calculated for phatbox, this dividend into that number.
							availableElSpace = $(window).height()-minPhatboxSpacing-130; // 10 less than minPhatboxSpacing to accommodate for weird width issues and scrollbar
						phatboxDataEl.css("max-height",availableElSpace);
						//setting the height for the height-fix the same as phatbox-data
						//phatboxHeightFix.css("height",availableElSpace);	


						//Set the popup window to center
						var offsetCenter = ($(window).height()/2-phatboxWrapperEl.height()/2)/2;
						phatboxWrapperEl.css('top', (offsetCenter < 0) ? 0 : (offsetCenter/offsetDividend));

			
						/*
						 * 3 types: 
						 * no scrollbar
						 * scrollbar
						 * forced scrollbar
						*/
						
						//setup scrollbar fix:

						if($("div.phatbox-data.scrollbar").length===1){
						//forced scrollbar
							//log("forced");
							var additionalOffset = 1;  //+1 for jacob.. idk
							phatboxDataEl.css("width",phatboxDataEl.innerWidth()+additionalOffset)
										 .css("padding-left","10px")
										 .css("padding-right","10px");
						} else if(phatboxDataEl.outerHeight() > availableElSpace){
						// we have a scroll bar 
							var scrollBarWidth = 15+2, //15 (scrollbar width)+ 2 (2 just incase)
								additionalOffset = 1;  //+1 for jacob.. idk
							phatboxDataEl.css("width",phatboxDataEl.innerWidth()+scrollBarWidth+additionalOffset)
										 .css("padding-left","10px")
										 .css("padding-right","10px");

						} else {
						// no scroll bar
							//phatboxDataEl.css("width",phatboxDataEl.innerWidth() +20);
							var additionalOffset = 1;  //+1 for jacob.. idk
							phatboxDataEl.css("width",phatboxDataEl.innerWidth()+additionalOffset)
										 .css("padding-left","10px")
										 .css("padding-right","10px");
						}
				
						$("#phatbox").css("width",phatboxDataEl.innerWidth()+2);	

						
						//clean up:
						lightboxRequest = null;
								
						//callback:
						if(callBackFunction && $.isFunction(callBackFunction))
							callBackFunction(phatboxWrapperEl); //pass parent back to callBack for reference

						//log to google (if it is google analytics is avail)
						if(typeof _gaq === 'object')
							_gaq.push(['_trackPageview', url]);
					});
};

window.openLightBox = openLightBox;
})($);


function closeLightBox(){
	return RentPost.UI.closeLightBox();
};


function showNotice(message,alert,delay){
	var alert = alert || false,
		notice = $("div.notice-thingy"),
		el = $("<span>"+message+"</span>");
	var delay = delay || 0;
	
	// add/remove Class & add onClick event Handler if alert
	if(alert){
		notice.addClass("error");
		$('<a class="close-notice" title="Close Error Notice" href="#"><img height="23" width="24" alt="x" src="/images/global/spacer.gif"></a>').click(function(event){
			event.preventDefault();
			$("div.notice-thingy").slideUp("slow");
		}).appendTo(el);
	} else {
		notice.removeClass("error");
	}
	
	// insert it and slide down	
	notice.animate({opacity: 1.0}, delay).html(el).slideDown("slow",function(){
		if(!alert){
			setTimeout('$("div.notice-thingy").slideUp("slow")', 3000);
		}
	});
};


/*
 * object.each(function(){ log(this) });
 */
//(function($) {
//	  var jq = $([]);
//	  $.fn.each = function(fn) {
//	   var i = -1,
//	       len = this.length,
//	       elem;
//	   while (++i < len && (elem = jq[0] = this[i]) && fn.call(elem, i, jq) !== false) {}
//	   delete jq[0];
//	   return this;
//	  };
//})(jQuery);

var RentPost = RentPost || {};
RentPost.UI = {
		showNotice: function(msg,alert,delay){
			var delay = delay || 0; 
			if(delay === true){ 
				delay = 400;
			}
			
			if(typeof showNotice == 'function' && $("div.notice-thingy").length){
				showNotice(msg,alert,delay);
			} else {
				alert(notice);
			}
			return this;
		},
		openLightBox: function(url,title,callBackFunction,titleMenu,forceTitleFormatting){
			// switch variables
			if(typeof callBackFunction == "string"){
				var fn = titleMenu || null; //incase it was null
				titleMenu = callBackFunction;
				callBackFunction = fn;
			}
			openLightBox(url,title,callBackFunction,titleMenu,forceTitleFormatting);
			return this;
		},
		closeLightBox: function(delay){
//			var delay = delay || 0;
//			if(delay === true){
//				delay = 400;
//			}
			var delay = delay === true ? 400:
						delay ? delay: 
						0;
			
			$("#phatbox-wrapper").animate({opacity: 1.0}, delay).fadeOut(300,function(event){
				$(this).css('top', '120px');
				$("#phatbox-body div.phatbox-data").removeAttr('style');
				$("#phatbox").css("max-width","500px");
				$("#phatbox-wrapper").removeAttr('style').hide();
				$("#phatbox-body").empty();
			});
			return this;
		},
		
		setLoadingCursour: function(el){
			document.body.style.cursor = "progress";
			if(el){
				$(el).css('cursor','progress');
			}
			return this;
		},
		removeLoadingCursour: function(el){
			document.body.style.cursor = "default";
			if(el){
				$(el).css("cursor","");
			}
			return this;
		}
};
RentPost.Utils = RentPost.Utils || {};
RentPost.Utils.sessonTimeOut = function(){
	notice ='You have been logged out. We are redirecting you to the login page.';
			
	RentPost.UI.showNotice(notice,true);
			
	setTimeout(function(){
		location.href = location.protocol+"//"+location.hostname+"/login";
	},3000);
};


Date.prototype.getMonthPlus = function(m){
	var copiedDate = new Date(this.getTime());
	copiedDate.setMonth(copiedDate.getMonth() + m);
	return copiedDate.getMonth();
};


//------
//
//  Error Handlers
//
//------

window.onerror = function(message){
	log(message);
};

function log(msg){
	// make sure we have console.log avail && we are in dev
	if (window.console && window.console.log) /* && baseUrl.indexOf("_dev") != -1)//window.console.firebug) */ 
	{
		console.log(msg);
	}
};

