/**
 * @author bcowan
 *0.9 - 2 - bcowan - 8 - 2008/11/22 :: Fixing overlay.hide and taboverlay things
 *0.9 - 1 - bcowan - 2008/11/14 :: Added title as second parameter to Overlay
 *0.8 - 2 - bcowan - 2008/10/10 :: Added Base64 and ezOpaque functions
 *0.8 - 1 - bcowan - 2008/10/03 :: added document.bz_msg and :msg_parent to $.bz.post for jGrowl msg in panels
 *0.4 - 1 - bcowan - 2008/09/26 :: Added $.bz.overlay function to be called insted of greybox...
 *0.3 - 1 - bcowan - 2008/09/13 :: First version with History, added toJson function
 */

 $.bz=new Object();
 $.bz.t=new Object();
 $.bz.msgLevel=5;
$.bz.msg=function(str,level,options)
{
	if (!level || level < $.bz.msgLevel) {
		if ($.jGrowl) {
			c=$(".msg_container");
			if(c.length==0) {c=$;};
			c.jGrowl(str, options);
		} else {
			alert(str);
		}
		
	}
 
}

document.bz_msg=$.bz.msg;
$.bz.alert = function(str){
	alert(str);
}

//Uses a modified RC4 cypher, seedhex is hexadecimal string
$.bz.t.seedhex="456bca";
$.bz.base64ToArray64=function(data64)
{
  var keyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var in_ar=new Array();
  for(var i=0;i<data64.length;i++) {
    idx=keyString.indexOf(data64[i]);
  //  if(idx>64) break;
    in_ar[i]=idx;
  }
  return in_ar;
}
$.bz.array64ToBase64=function(ar64)
{
  var keyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var in_str="";
  for(var i=0;i<ar64.length;i++) {
    in_str+=keyString[ar64[i]];
  }
  //in_str += (in_str.length%3>0 ? ( in_str.length%3 >1 ? "==" : "=") : "");
  return in_str;
}
$.bz.ezOpaque64=function(data64,seedhex)
{
  
  seedhex=seedhex || $.bz.t.seedhex;
  seed_c=new Array();
  var i,j,t;
  t=0;
  for(i=0;i<seedhex.length;i+=2){

    eval('seed_c[t]= 0x'+seedhex.substr(i,2)+' & 63');
    t++;
  }
 
  i = 0;
  j = 0;
 
  in_ar=$.bz.base64ToArray64(data64);
  
  out_ar=new Array();
  for(var c=0;c<in_ar.length;c++){
    i = (i + 1) % seed_c.length
    j = (j + seed_c[i]) % seed_c.length
    var t=seed_c[i];seed_c[i]=seed_c[j];seed_c[j]=t;
    var k=seed_c[(seed_c[i] + seed_c[j]) % seed_c.length];
    out_ar[c]=in_ar[c] ^ k;
   
  }
  
  return $.bz.array64ToBase64(out_ar);
}


$.bz.ezOpaque=function(data,seedhex)
{
  seedhex=seedhex || $.bz.t.seedhex;
  seed_c=new Array();
  var i,j,t;
  t=0;
  for(i=0;i<seedhex.length;i+=2){

    eval('seed_c[t]= 0x'+seedhex.substr(i,2));
    t++;
  }
 
  i = 0;
  j = 0;
  in_str="ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt";
  while(in_str.length<256) {in_str+="t";}
  in_str+=data;
  out_str="";
  for(var c=0;c<in_str.length;c++){
    i = (i + 1) % seed_c.length
    j = (j + seed_c[i]) % seed_c.length
    var t=seed_c[i];seed_c[i]=seed_c[j];seed_c[j]=t;
    var k = seed_c[(seed_c[i] + seed_c[j]) % seed_c.length];
    out_str+=String.fromCharCode(in_str.charCodeAt(c) ^ k);
   
  }
  
  return out_str.substr(256);
}

$.bz.post=function(controller,id,action,call_params,recall_params)
{
	if(!call_params) {
	   call_params=new Object();
	  
	}
        if(!call_params.authenticity_token){
             call_params.authenticity_token=authenticity_token;
        }

 // call_params.opaqued=$.base64Encode($.bz.ezOpaque("sample, esto es un ejemplo de 54632"));
  //call_params.opaqued=$.bz.ezOpaque64($.base64Encode("abcdefghijkl"));
 	$.post('/'+controller+'/'+(id!=null ? id+'/' : '')+action+'.js',call_params,function(data){
		var ret;
       
		eval('ret='+data);
		if(ret.msg){$.bz.msg(ret.msg,4);}
    if(ret.msg_parent){if(window.parent!=null && window.parent.document.bz_msg!=null){window.parent.document.bz_msg(ret.msg_parent,3);}}
		if (ret.reload_parent) {
			var wp = window.parent;
			if (wp) {
				wp.GB_callback = function(){
					wp.window.location.reload();
				};
			}
		}
		if(ret.eval){eval(ret.eval);}
		if(ret.reload) {window.location.reload();}
		
    if(ret.close_gb) {var wp = window.parent;
			if (wp) {
				wp.$('#GB_closewindow').click();
			}
    }
	});
       
}


$.bz.submitForm=function(controller,id,action,form,recall_params)
{
	params=new Object();
	$(form).find('[name]').each(function() {
		it=$(this);	
	    if((it.attr('type')!="radio" && it.attr('type')!="checkbox") || this.checked) {	
			params[it.attr('name')]=it.val();
		}
	});
	$.bz.post(controller,id,action,params,recall_params);
	return false;
}

//Taken from http://devers.blogspot.com/2007/09/worlds-smallest-tojson-function.html
$.bz.toJson=function(obj) {
 switch (typeof obj) {
  case 'object':
   if (obj) {
    var list = [];
    if (obj instanceof Array) {
     for (var i=0;i < obj.length;i++) {
      list.push($.bz.toJson(obj[i]));
     }
     return '[' + list.join(',') + ']';
    } else {
     for (var prop in obj) {
      list.push('' + prop + ':' + $.bz.toJson(obj[prop]));
     }
     return '{' + list.join(',') + '}';
    }
   } else {
    return 'null';
   }
  case 'string':
   return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
  case 'number':
  case 'boolean':
   return new String(obj);
 }
}

//obj is either and anchor object, a url (prepended with url=), a div, a string, rendered into a default format,
//or an object with more options
//TODO: Finish this function, currently only works with anchor objects
//Currently uses GreyBox
var GB_ANIMATION = true;    
$.bz.overlay=function(obj,intitle)
{
  var url=null;
  var title=null;
  var content=null;
  if(typeof(obj)=="object") {
    if(typeof(obj.tagName)=="string" && obj.tagName=="A") {
      url=obj.attributes.href.nodeValue;
      title=(typeof(obj.attributes.title)=="object" ? obj.attributes.title.nodeValue : ($.bz.t.defaultOverlayTitle || url));
      
      GB_show(title,url,470,600);//, height, width,callback) 
    
    } else if(obj.minitab) {
      url=obj.url;
      content=obj.html_content;
      title=obj.title || $.bz.t.defaultOverlayTitle || obj.url;
      if(content!=null) {
        $.bz.taboverlay.showfunction(title,content);
      } else if(url!=null) {
        $.bz.taboverlay(title,url);
      } else {
        $.bz.msg("Error en Interfaz... #A01")
      }
    } else if(obj.greybox) {
      url=obj.url;
      content=obj.html_content;
      title=obj.title || $.bz.t.defaultOverlayTitle || obj.url;
      if(content!=null) {

      } else if(url!=null) {
        GB_show(title,url,470,600);
      } else {
        $.bz.msg("Error en Interfaz... #A02")
      }
    } else {
      $.bz.msg("Error en Interfaz... #A03")
    }    
  } else if (typeof(obj)=="string") {
    
    url=obj;
    title=intitle || ($.bz.t.defaultOverlayTitle || url);
    
    GB_show(title,url,470,600);
  } 
}
$.bz.overlay.close=function(){GB_hide();}


$.bz.taboverlay=function(caption,url,callback)
{    
   $.bz.taboverlay.showfunction(caption,"cargando...",callback);//, height, width,callback)
   $("#BZTAB_content").load(url);
}

$.bz.picoverlay=function(src,callback,src2)
{    
   $.bz.picoverlay.showfunction(src,callback,src2 || null);//, height, width,callback)
  
}


var BZT_callback=null;
var BZTi_callback=null;
var BZT_DONE=false;
var BZT_DONEi=false;

var BZT_ANIMATION=true;
var BZTi_ANIMATION=true;
$.bz.taboverlay.hide=function()
{
  $("#BZTAB_window,#BZTAB_overlay").hide();
    if(BZT_callback) {BZT_callback();}
}
$.bz.taboverlay.showfunction=function(caption, html,callback) {

  var bzt_hide=function() {
    $("#BZTAB_window,#BZTAB_overlay").hide();
    if(BZT_callback) {BZT_callback();}
  };

  var bzt_position=function() {
    var de = document.documentElement;
    var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
    $("#BZTAB_window").css({width:"392px",height:"189px",
      left: ((w - 392)/2)+"px" });
   // $("#GB_frame").css("height",GB_HEIGHT - 12 +"px");
  };
  if(!BZT_DONE) {
    
    var a=$(document.body);
   

    a.append(
        '<div id="BZTAB_overlay" style="background: #353535; position: absolute; margin: auto; top: 0; left: 0; z-index: 1000; width:  100%; height: 100%; opacity: .7;">&nbsp;</div>'+
        '<div id="BZTAB_window" style="display:block;z-index:1400;top:150px;width:392px;position:absolute;">'+
          '<table cellspacing="0" style="width:392px" valign="top"><tr><td style="background:url(/img/tab-top.png);height:49px;padding:0px;">'+
            '<div id="BZTAB_closetab" style="padding:0px;position:absolute;color: white;cursor:pointer;height:20px;width:20px;margin-left:0px;margin-top: -13px;position:absolute;z-index:5000" onclick="$.bz.taboverlay.hide()">(close)</div>'+
            '<div id="BZTAB_caption" style="color:white;margin-top: -3px;margin-left:20px;text-align:center;width:100px;font-family: Helvetica; font-size: 18px;">&nbsp;</div>'+
          '</td></tr><tr><td style="width:392px;background:url(/img/tab-mid.png)">'+
            '<div id="BZTAB_content" class="textoMasBonito" style="text-align:justify;font-size:12px;margin-left:15px;width: 352px;margin-right:25px;">&nbsp</div>'+
          '</td></tr><tr><td style="background:url(/img/tab-bot.png) top no-repeat;height:49px;"><div style="height:49px">&nbsp;</div>'+
         '</td></tr></table>'+
        //'</div>'+
        '</div>'
       );
   
    //$("#BZTAB_closetab").click(bzt_hide);
    $("#BZTAB_overlay").click(bzt_hide);
    $(window).resize(bzt_position);
    BZT_DONE = true;
   
  }

  //$("#GB_frame").remove();
  //$("#GB_window").append("<iframe id='GB_frame' src='"+url+"'></iframe>");

  $("#BZTAB_caption").html(caption);
  $("#BZTAB_content").html(html);
  $("#BZTAB_overlay").show();
  bzt_position();

  if(BZT_ANIMATION)
    $("#BZTAB_window").show();//slideDown("slow");
  else
    $("#BZTAB_window").show();


  BZT_callback=callback;
 
}

$.bz.picoverlay.showfunction=function(src,callback,src2) {

  var bzt_hide=function() {
    $("#BZTABi_window,#BZTABi_overlay").hide();
    if(BZTi_callback) {BZTi_callback();}
  };

  var bzt_position=function() {
    var de = document.documentElement;
    var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
    $("#BZTABi_window").css({width:"514px",height:"329px",
      left: ((w - 514)/2)+"px" });
   // $("#GB_frame").css("height",GB_HEIGHT - 12 +"px");
  };
  if(!BZT_DONEi) {
    $(document.body)
      .append(
        '<div id="BZTABi_overlay" style="background:url('+(src2 || '/img/spaced/nope.jpg')+') center 0; position: absolute; margin: auto; top: 0; left: 0; z-index: 1000; width:  100%; height: 100%; opacity: .25;display:block;"></div>'+
        '<div id="BZTABi_window" style="cursor:pointer;display:none;background:url('+src+');z-index:1400;top:150px;width:514px;height:329px;position:absolute;overflow:hidden;">'+
            '&nbsp;'+
        '</div>'
       );
    $("#BZTABi_window").click(bzt_hide);
    $("#BZTABi_overlay").click(bzt_hide);
    $(window).resize(bzt_position);
    BZT_DONEi = true;
   
  }
  $("#BZTABi_overlay").show();
  bzt_position();

  if(BZTi_ANIMATION)
    $("#BZTABi_window").slideDown("slow");
  else
    $("#BZTABi_window").show();

	
  BZTi_callback=callback;
}




