function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
function substr_count(_string,substring,start,length) {
	var c = 0;
	if(start) { _string = _string.substr(start); }
	if(length) { _string = _string.substr(0,length); }
	for (var i=0;i<_string.length;i++) {
		if(substring == _string.substr(i,substring.length))
		c++;
	}
	return c;
}


var makeEach = function(data) {
	if(data.xhtml) {
		if($('meta[name="id"]').attr('content')!=data.xhtml.id) {
			$('meta[name="id"]').attr('content', data.xhtml.id);
			document.body.innerHTML = data.xhtml.html;
		}
	}
	$.each(data.ids, function(i,item){
		$('#'+item.id).html(item.html);
		loadContent(item);
	});
	loading.stop();
}

function fLink(href) {
	href = href||"";
	var local = 1;
	if(href.indexOf("http://")==0) {
		if(href.indexOf(base)!=0) {
			local = 0;
		}
	}
	if(local) {
		var next = href;
		next = (next==current)?next+"/":((next==undefined)?base+"/":next);
		var checkNext = substr_count(current.replace(base,""),"/",0,-1);
		if(checkNext>0) {
			for(var i=0;i<checkNext;i++) {
				next = "../"+next;
			}
		}
		loading.start();
		$.ajax({
			url:next,
			dataType: "json",					
			success:function(data){
				makeEach(data);
			},
			error: function (xhr, desc, exceptionobj) {
				alert("Ocorreu um erro com a aplica\xE7\xE3o. Provavelmente este link est\xE1 quebrado.");
				loading.stop();
			}
		});
		e.preventDefault();
	} else {
		$(this).attr(href,"_blank");
	}
}

var binding = {
	all: function(item) {
		var _base = (item)?"#"+item.id+" ":"";
		$(_base+' a').bind("click", function(e){
			if($(this).hasClass('leaveMe')) return;
			this.href = this.href||"";
			var local = 1;
			if($(this).attr('href').indexOf("http://")==0) {
				if($(this).attr('href').indexOf(base)!=0) {
					local = 0;
				}
			}
			if(local) {
				var next = $(this).attr('href');
				next = (next==current)?next+"/":((next==undefined)?base+"/":next);
				//CHECK THIS ON IE
				var checkNext = substr_count(current.replace(base,""),"/",0,-1);
				if(checkNext>0) {
					for(var i=0;i<checkNext;i++) {
						next = "../"+next;
					}
				}
				//CHECK THIS ON IE
				loading.start();
				$.ajax({
					url:next,
					dataType: "json",					
					success:function(data){
						makeEach(data);
					},
					error: function (xhr, desc, exceptionobj) {
						alert("Ocorreu um erro com a aplica\xE7\xE3o. Provavelmente este link est\xE1 quebrado.");
						loading.stop();
					}
				});
				e.preventDefault();
			} else {
				$(this).attr("target","_blank");
			}
		});/*
		$(_base+'img').hover(function(){
			var videoId = $(this).attr('src').replace('http://img.youtube.com/vi/','');
			videoId = videoId.substring(0,videoId.indexOf('/'));
			var img = $(this);
			var count = 0;
			mouseOverImg = periodical(function() {
				count = (count<3)?(count+1):1;
				var src = 'http://img.youtube.com/vi/'+videoId+'/'+count+'.jpg';
				img.attr('src', src);
			}, 1000);
			}, function() {
				window.clearInterval(mouseOverImg);
			}
		); */
		$(_base+' form').bind('submit',function(e) {
			var local = 1;
			if($(this).attr('action').indexOf("http://")==0) {
				if($(this).attr('action').indexOf(base)!=0) {
					local = 0;
				}
			} else {
				//CHECK THIS ON IE
				var checkNext = substr_count(current.replace(base,""),"/",0,-1)
				next = "";
				if(checkNext>0) {
					for(var i=0;i<checkNext;i++) {
						next = "../"+next;
					}
				}
				$(this).attr('action',next+$(this).attr('action'));
				//CHECK THIS ON IE
			}
			$(_base+"form .wymeditor").each(function() {
				var txtValue = $(this);
				txtValue.val(txtValue.htmlarea('toHtmlString'));
			});
			if(local) {
				e.preventDefault();
				loading.start();
				$(this).ajaxSubmit({
					dataType:'json',
					beforeSubmit:function(formData, jqForm, options) {
						var formElement = jqForm[0];
						$(formElement).prepend($("<input type='hidden' name='xhr' value='true'/>"));
						return true;
					},
					success:function(data) {
						$.each(data.ids, function(i,item){
							$('#'+item.id).html(item.html);
							loadContent(item);
						});
						loading.stop();
					}
				});
				return false;
			} else if($(this).hasClass('self')) {
				loading.start();
				e.preventDefault();
				loading.start();
				$(this).ajaxSubmit({
					success:function(formData, jqForm, options) {
						var data = {xhtml:{html:formData},force:1}
						makeEach(data);
						return true;
					}
				});
				return false;
			}
		});
		if(typeof $(_base+' .wymeditor').htmlarea == "function") {
			$(_base+' .wymeditor').htmlarea({
				toolbar: ["html","|","bold","italic","underline","strikethrough","|","subscript","superscript","|","increasefontsize","decreasefontsize","|","forecolor","|","orderedlist","unorderedlist","|","indent","outdent","|","justifyleft","justifycenter","justifyright","|","link","unlink","image","|","h3","h4","h5","h6","|","cut","copy","paste"]
			});
		}
		jtip();
	}
}
loadContent = function(item) {
	binding.all(item);
}
$(document).ready(function () {
	binding.all();
	jQuery.fn.centerScreen = function(loaded) {
		var obj = this;
		var _top = f_scrollTop();
		var _left = f_scrollLeft();
		if(!loaded) {
			obj.css('top', _top);
			obj.css('left', _left);
			$(window).resize(function() {obj.centerScreen(!loaded);});
			$(window).scroll(function() {obj.centerScreen(!loaded);});
		} else {
			obj.stop();
			obj.animate({top:_top,left:_left},200,'linear');
		}
	}
	
});

var loading = {
	start: function(p) {
		var getDoc = (p) ? parent.document : document ;
		var load = getDoc.createElement('div');
		var msg = getDoc.createElement('div');
		$(msg).css({
			margin : "190px auto",
			width : "400px",
			width : "300px",
			textAlign : "center",
			color: "#fff"
		}).html('Carregando...');
		//var opacity = 50;
		$(load).attr('id','__xLoading').css({
			position: "absolute",
			background : "#000",
			color: "#fff",
			opacity: 0.8, // for all browsers except IE
			filter: 'alpha(opacity = 80)', // for IE
			width: "100%",
			height: f_clientHeight()+"px",
			top: "0",
			left: "0",
			zIndex: "99"
		}).prepend(msg);
		$(getDoc.body).prepend(load);
		$(load).centerScreen();
	},
	stop: function(p) {
		var getDoc = (p) ? parent.document : document ;
		$(getDoc.getElementById('__xLoading')).remove();
	}
}

function print_r(theObj) {
	if(theObj.constructor == Array || theObj.constructor == Object) {
		document.write("<ul>");
		for(var p in theObj) {
			if(theObj[p].constructor == Array || theObj[p].constructor == Object){
				document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
				document.write("<ul>");
				print_r(theObj[p]);
				document.write("</ul>");
			} else {
				document.write("<li>["+p+"] => "+theObj[p]+"</li>");
			}
		}
		document.write("</ul>");
	}
}

