
$(function(){
	
	$("#phatbox-header > a").click(function(event){
		event.preventDefault(); event.stopPropagation();
		closeLightBox();
	});	
	
	
	// basic error handler (and denying of cache for IE issues)
	$.ajaxSetup({
		cache: false,
		error :function(XMLHttpRequest,textStatus, errorThrown) {
			var notice = '';
			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 with case number '+XMLHttpRequest.getResponseHeader("X-Error-Code");
			}else if(XMLHttpRequest.status == 401){
				notice ='You have been logged out. We are redirecting you to the login page.';
				location.href = location.protocol+"//"+location.hostname+"/login";
			}else if(errorThrown=='parsererror'){
				notice = 'Error.\nParsing JSON Request failed.';
			}else if(errorThrown=='timeout'){
				notice = 'Request Time out.';
			}else {
				//notice = 'Unknow Error.';
				return;
			}
			
			//use showNotice if we have it avail
			if(typeof showNotice == 'function')
				showNotice(notice,true);
			else
				alert(notice);
			
			log(XMLHttpRequest);
			log(textStatus);
			log(errorThrown);
		}
	});
	
	
	// :: footer ::		
	$("#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
//
//------

var lightboxRequest;
function openLightBox(url,title,callBackFunction,titleMenu){
	var phatboxWrapperEl = $("#phatbox-wrapper");
	
	// cleanup
	$("#phatbox-body").empty().removeAttr("style");
	if(lightboxRequest)
		lightboxRequest.abort();

	phatboxWrapperEl.css("display","block");
	
	//format title:
	title = title.capitalize();
	
	//title menu is for add/remove/edit functionality
	if(titleMenu)
		title = title+ " " +titleMenu;
	
	$("#phatbox-header h1").html(title);

	lightboxRequest = $.get(url, function(data) {
		
						//was this aborted?
						if(lightboxRequest.status != 200)
							return;
				
						$("#phatbox-body").html(data);
				
						$("#phatbox").removeAttr("style"); // no clue how this gets a style :/ - it gets a style from html or prev cache'd boxes ;)
						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 = 140,
							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");
						}
				
						//new addition
						$("#phatbox").css("width",phatboxDataEl.innerWidth()+2);
	 				

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



function closeLightBox(){
	$("#phatbox-wrapper").fadeOut(200,function(event){
		$(this).css('top', '120px');
		$("#phatbox-body div.phatbox-data").removeAttr('style');
		$("#phatbox").css("max-width","500px");
		$("#phatbox-body").empty();
	});
}


function showNotice(message,alert){
	var alert = alert || false;
	var notice = $("div.notice-thingy");
	var el = $("<span>"+message+"</span>");
	
	// 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.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);





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

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

function log(msg){
	if (window.console && window.console.log)//window.console.firebug) 
	{
		console.log(msg);
	}
}