$(document).ready(function()
{
	$("a.ui[rel]").colorbox();
});

function get_content(idc)
{
	if(idc.search("block_")==-1)
	{
		var url      = $.url();
		var data_url = "idc=" + idc + "&" + url.attr('query');
		$.ajax(
		{
		   type: "POST",
		   url:  "includes/handle_url.php",
		   data: data_url,
		   success: function(content)
		   {
			   if(content==-1)
			   {
				   $.colorbox({ transition:"elastic", html: "<div class='error'>Ocorreu um erro! <br><br> Tente mais tarde ou reporte a situa&ccedil;&atilde;o!</div>" });
			   }
			   else
			   {
				   try
				   {
					   var splitted     = new Array(); var i = 0;
					   var novoTotal_je = eval('(' + content + ')');
					   for(var key in novoTotal_je)
					   {
						   splitted[i] = novoTotal_je[key];
						   i++;
					   }

					   if(splitted[0]!="")
							$.colorbox({ transition:"elastic", overlayClose:true, html: splitted[0] });
					   if(splitted[1]!="")
							eval(splitted[1]);
				   }
				   catch(err)
				   {
						$.colorbox({ transition:"elastic", html: "<div class='error'>Ocorreu um erro! <br><br> Tente mais tarde ou reporte a situa&ccedil;&atilde;o!</div>" });
				   }
			   }
		   }
		});
	}
	else
	{
		var idb = idc.split("_");
		get_block(idb[1]);
	}
}

function get_content_categories(idct,idc)
{
   var url      = $.url();
   var data_url = "idct=" + idct + "&idc=" + idc + "&" + url.attr('query');
   $.ajax(
   {
       type: "POST",
       url:  "includes/handle_url.php",
       data: data_url,
       success: function(content)
       {
           if(content==-1)
           {
               $.colorbox({ transition:"elastic", html: "<div class='error'>Ocorreu um erro! <br><br> Tente mais tarde ou reporte a situa&ccedil;&atilde;o!</div>" });
           }
           else
           {
               try
               {
                   var splitted     = new Array(); var i = 0;
                   var novoTotal_je = eval('(' + content + ')');
                   for(var key in novoTotal_je)
                   {
                       splitted[i] = novoTotal_je[key];
                       i++;
                   }

				   if(splitted[0]!="")
						$.colorbox({ transition:"elastic", overlayClose:true, html: splitted[0] });
				   if(splitted[1]!="")
						eval(splitted[1]);
               }
               catch(err)
               {
					$.colorbox({ transition:"elastic", html: "<div class='error'>Ocorreu um erro! <br><br> Tente mais tarde ou reporte a situa&ccedil;&atilde;o!</div>" });
               }
           }
       }
    });
}

function get_comment(idc)
{
   var url      = $.url();
   var data_url = "comment=" + idc + "&" + url.attr('query');
   $.ajax(
   {
       type: "POST",
       url:  "includes/handle_url.php",
       data: data_url,
       success: function(content)
       {
           if(content==-1)
           {
               $.colorbox({ transition:"elastic", html: "<div style='color: red; width: 100%; text-align: center;'>Ocorreu um erro! <br><br> Tente mais tarde ou reporte a situa&ccedil;&atilde;o!</div>" });
           }
           else
           {
               try
               {
                   var splitted     = new Array(); var i = 0;
                   var novoTotal_je = eval('(' + content + ')');
                   for(var key in novoTotal_je)
                   {
                       splitted[i] = novoTotal_je[key];
                       i++;
                   }

				   if(splitted[0]!="")
						$.colorbox({ transition:"elastic", overlayClose:true, html: splitted[0] });
				   if(splitted[1]!="")
						eval(splitted[1]);
               }
               catch(err)
               {

               }
           }
       }
    });
}

function get_image(img)
{
	var image = new Image(); 
	image.src = img;
	open_colorbox("<img class='syslbimage' src='"+img+"' />");
}

function get_new_image(thi,img)
{
	//image
	var image = new Image(); 
	image.src = img;
	
	//rel
	if ($(thi).attr("rel"))
	{
		open_colorbox_rel(thi,img,$(thi).attr("rel"));
	}
	else
	{
		open_colorbox("<img class='syslbimage' src='"+img+"' />");
	}
}

function get_content_url()
{
   var url      = $.url();
   var data_url = url.attr('query');
   $.ajax(
   {
       type: "POST",
       url:  "includes/handle_url.php",
       data: data_url,
       success: function(content)
       {
           if(content==-1)
           {
               $.colorbox({ transition:"elastic", html: "<div style='color: red; width: 100%; text-align: center;'>Ocorreu um erro! <br><br> Tente mais tarde ou reporte a situa&ccedil;&atilde;o!</div>" });
           }
           else
           {
               try
               {
                   var splitted     = new Array(); var i = 0;
                   var novoTotal_je = eval('(' + content + ')');
                   for(var key in novoTotal_je)
                   {
                       splitted[i] = novoTotal_je[key];
                       i++;
                   }
                   $.colorbox({ transition:"elastic", overlayClose:true, html: splitted[0] });
               }
               catch(err)
               {
                   $.colorbox({ transition:"elastic", html: "<div style='color: red; width: 100%; text-align: center;'>Ocorreu um erro! <br><br> Tente mais tarde ou reporte o problema!</div>" });
               }
           }
       }
    });
}

function get_block(idb)
{
	var data_url = "idb=" + idb;
	$.ajax(
	{
       type: "POST",
       url:  "includes/handle_url.php",
       data: data_url,
       success: function(content)
       {
           if(content==-1)
           {
               $.colorbox({ transition:"elastic", html: "<div class='error'>Ocorreu um erro! <br><br> Tente mais tarde ou reporte a situa&ccedil;&atilde;o!</div>" });
           }
           else
           {
               try
               {
					var splitted     = new Array(); var i = 0;
					var novoTotal_je = eval('(' + content + ')');
					for(var key in novoTotal_je)
					{
						splitted[i] = novoTotal_je[key];
						i++;
					}

					if(splitted[0]!="")
						$.colorbox({ transition:"elastic", overlayClose:true, html: splitted[0]+"<style>"+splitted[2]+"</style>" });
					if(splitted[1]!="")
						eval(splitted[1]);
               }
               catch(err)
               {
					$.colorbox({ transition:"elastic", html: "<div class='error'>Ocorreu um erro! <br><br> Tente mais tarde ou reporte a situa&ccedil;&atilde;o!</div>" });
               }
           }
       }
	});
}

/*
 *  OPEN COLORBOX
 */
function open_colorbox(html)
{
    $.colorbox({transition: "elastic", 
				html: 		"<div style='color: green; width: 100%; text-align: center;'>" + html + "</div>" });
}

function open_colorbox_2(html)
{
    var html2 = urlDecode(html);
    $.colorbox({ height: 	 "80%", 
				 width: 	 "50%", 
				 transition: "elastic", 
				 html: 		 "<div style='color: green; width: 100%; text-align: center;'>" + html2 + "</div>" });
}

function get_colorbox_html_this(id)
{
	var html  = $(id).html();
    var html2 = urlDecode(html);
    $.colorbox({ overlayClose:true, transition:'elastic', html: html2 });
}

function open_colorbox_rel(thi,img,rela)
{
	$.colorbox(
	{
		transition: "elastic", 
		html:		"<div style='color: green; width: 100%; text-align: center;'><img class='syslbimage' src='"+img+"' /></div>",
		rel: 		rela 
	});
}

/*
 *  CALL URL
 */ 
function call_url(url)
{
	window.location.href = url;
}

/*
 *  SEARCH
 */
function v_search2()
{
	var a = $('#search_input').val();
	if(a != null && a != 'Search' && a != '')
		return true;
	else
		return false;
}
							
function v_search(idbs,w,h,code)
{
    var a = $('#search_input').val();
    if(a != null && a != 'Search' && a != '')
    {
        var data_url = 's='+a+'&sb='+idbs+'&code='+code;
        $.ajax(
        {
           type: 'POST',
           url:  'includes/handle_url.php',
           data: data_url,
           success: function(content)
           {
               if(content==-1)
               {
                   $.colorbox({ transition:'elastic',
                                html: "<div style='color: red; width: 100%; text-align: center;'>Ocorreu um erro! <br><br> Tente mais tarde ou reporte a situa&ccedil;&atilde;o!</div>" });
               }
               else
               {
                   var splitted     = new Array(); var i = 0;
                   var novoTotal_je = eval('(' + content + ')');
                   for(var key in novoTotal_je)
                   {
                       splitted[i] = novoTotal_je[key];
                       i++;
                   }
                   $.colorbox({ height: h,
                                width: w,
                                transition:'elastic',
                                overlayClose:true,
                                html: splitted[0] });
               }
           }
		});
    }
}

/*
 *  REQUEST BLOCK
 */
function request_ajax_block(block,info)
{
	$.ajax(
    {
       type: 'POST',
       url:  'includes/submit.php',
       data: 'op=block&op2=linguas&op3='+block+'&info='+info,
       success: function(content)
       {
			if(content==1)
				window.location.reload();
	   }
	});
}

function ajax_request(op,op2,op3,info)
{
	$.ajax(
    {
       type: 'POST',
       url:  'includes/handle_url.php',
       data: 'op='+op+'&op2='+op2+'&op3='+op3+'&info='+info,
       success: function(content)
       {
			if(content==-1) { }
			else if(content==1)	
				window.location.reload();
			else
			{
				var splitted     = new Array(); var i = 0;
                var novoTotal_je = eval('(' + content + ')');
                for(var key in novoTotal_je)
                {
                   splitted[i] = novoTotal_je[key];
                   i++;
                }

				if(splitted[0]=="colorbox")
				{
					$.colorbox({ transition:"elastic", overlayClose:true, html: splitted[1] });
					eval(splitted[2]);
				}
				else if(splitted[0]=="url")
				{
					window.location.href = splitted[1];
				}
			}
	   }
	});
}

/*
 *
 * OTHERS
 *
 */
function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

function jq_URLEncode(c)
{
    var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
    while(x<c.length){var m=r.exec(c.substr(x));
    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}
    return o;
}

function jq_URLDecode(s)
{
    var o=s.replace(/\+/g,' ');var binVal,t;var r=/(%[^%]{2})/;
    while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
    t=String.fromCharCode(b);o=o.replace(m[1],t);}
    return o;
}

function urlDecode(str)
{
    return jq_URLDecode(str);
}

var Utf8 = {
 // public method for url encoding
 encode : function (string) {
 string = string.replace(/\r\n/g,"\n");
 var utftext = "";
 
 for (var n = 0; n < string.length; n++) {
  var c = string.charCodeAt(n);
  if (c < 128) {
   utftext += String.fromCharCode(c);
  }
  else if((c > 127) && (c < 2048)) {
   utftext += String.fromCharCode((c >> 6) | 192);
   utftext += String.fromCharCode((c & 63) | 128);
  }
  else {
   utftext += String.fromCharCode((c >> 12) | 224);
   utftext += String.fromCharCode(((c >> 6) & 63) | 128);
   utftext += String.fromCharCode((c & 63) | 128);
  }
 }
 return utftext;
},

 // public method for url decoding
 decode : function (utftext) {
  var string = "";
  var i = 0;
  var c = c1 = c2 = 0;
  
  while ( i < utftext.length ) {
   c = utftext.charCodeAt(i);
   if (c < 128) {
    string += String.fromCharCode(c);
    i++;
   }
   else if((c > 191) && (c < 224)) {
    c2 = utftext.charCodeAt(i+1);
    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
    i += 2;
   }
   else {
    c2 = utftext.charCodeAt(i+1);
    c3 = utftext.charCodeAt(i+2);
    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
    i += 3;
   }
  }
  return string;
 }
}

/*
 *
 * FACEBOOK
 *
 */
var fbApiInit = false; var fbApiId = ''; var fbApiAccessToken = ''; var permsNeeded = []; var permsGeneric = "";

// Function that checks needed user permissions
var checkPermissions = function() 
{
  	FB.api('/me/permissions', function(response) 
	{	
		var permsArray 	  = response.data[0];
		var permsToPrompt = [];
		for (var i in permsNeeded) 
		{
		  	if(permsNeeded[i] != '' && permsNeeded[i] != 'undefined' && permsNeeded[i] != null)
		  	{
				if (permsArray[permsNeeded[i]] == null) 
				{
					permsToPrompt.push(permsNeeded[i]);
				}
			}
		}
		if (permsToPrompt.length > 0) { promptForPerms(permsToPrompt); } 
		else { }
  	});
};

// Re-prompt user for missing permissions
var promptForPerms = function(perms) 
{
	FB.login(function(response) {
	  console.log(response);
	}, {scope: perms.join(',')});
};

// ensure FB Init
function fbEnsureInit(callback) 
{
	if(!window.fbApiInit) {
		setTimeout(function() {fbEnsureInit(callback);}, 50);
	} else {
		if(callback) {
			callback();
		}
	}
}


// get fb friends
function get_fb_friends(div)
{
	$.ajax(
   	{
       	type: "POST",
       	url:  "includes/social_blocks.php",
       	data: "op=facebook&fb=amigos",
		dataType: "json",
		error: function()
		{
			return -1;
		},	
       	success: function(data)
       	{
			/*var aux = "";
			$.each(data, function(i, item) 
			{
				aux += "<div><img src='"+item.picture+"'</div>";
		  	});
			$("#"+div).html(aux);*/
			return data;       	
       	}
	});
}

// do fb login
function fb_login()
{
	// fb login
	FB.getLoginStatus(function(response) 
	{
		if (response.authResponse) 
		{
			fbApiAccessToken = response.authResponse.accessToken;

			checkPermissions();

			FB.api('/me', function(response) 
			{ 
				fbApiId = response.id;
			});

			// flag fb init correct
			fbApiInit = true;

			// fetch all fb data to db
			$.ajax(
		   	{
			   	type: 'POST',
			   	url:  'includes/social_blocks.php',
			   	data: 'op=facebook&fb=getdata'
			});
		} 
		else 
		{
			FB.login(function(response) 
			{
				if (response.authResponse) 
				{
					alert('Welcome!  Fetching your information.... ');
					checkPermissions();

					fbApiAccessToken = response.authResponse.accessToken;
					FB.api('/me', function(response) 
					{ 
						fbApiId = response.id;
					});

					// flag fb init correct
					fbApiInit = true;

					window.location.reload();
				} 
				else 
				{
					alert('User cancelled login or did not fully authorize.');
				}
		 	}, {scope: permsGeneric});
		}
	}, true);
}

