// Create BT namespace if necessary
if (!window.BT) {
  BT = {};
}

// Only load if this class is not already loaded
if (!BT.Bootstrap) {
  BT.Bootstrap = {
    init : function(sig_key, xd_receiver, callback) {
	  // init has changed definition by now
	  BT.Orori.init(sig_key, xd_receiver, callback);
    },
    addScript : function(src) {
      var scriptElement;

      // Check if we have the script loaded already
      var scriptElements = document.getElementsByTagName('script');
      if (scriptElements ) {
        var c = scriptElements.length;
        for (var i = 0; i < c; i++) {
          scriptElement = scriptElements[i];
          if (scriptElement.src == src) {
            // Found a match
            return;
          }
        }
      }
      scriptElement = document.createElement("script");
      scriptElement.type = "text/javascript";
      scriptElement.src = src;
      var parent = document.getElementsByTagName('HEAD')[0] || document.body;
      parent.appendChild(scriptElement);
    },
    initializeXdChannel : function () {
        BT.Bootstrap.createHiddenDiv();
    },
    createHiddenDiv : function() {
      if (document.getElementById('X_HiddenContainer') == null) {
        document.write('<div id="X_HiddenContainer" '
                       + 'style="position:absolute; top:-10000px; left:-10000px; width:0px; height:0px;" >'
                       + '</div>');
      }
    },
    detectDocumentNamespaces : function() {
      if (document.namespaces && !document.namespaces.item['bt']) {
        document.namespaces.add('bt');
      }
    }
  };

  /*
   * Define shorthand functions for ease of use.
   */
  window.BT.init= BT.Bootstrap.init;
}

BT.Bootstrap.initializeXdChannel();
BT.Bootstrap.detectDocumentNamespaces();

// Create BTIntern namespace if necessary
if (!window.BTIntern) {
  BTIntern = {};
}

// Only load if this class is not already loaded
if (!BTIntern.XdReceiver) {
  // XdReceiver class
  BTIntern.XdReceiver = {
    delay : 100,
    timerId : -1,
    dispatchMessage: function() {
      //We don't used window.location.hash because it has different behavior on IE and Firefox.
      //See https://bugzilla.mozilla.org/show_bug.cgi?id=378962
      var pathname = document.URL;
      var hashIndex = pathname.indexOf('#');
      var hash;
      if(hashIndex > 0) {
        hash = pathname.substring(hashIndex + 1);
      } else {
        //hashIndex not found;
        //Check if it's special case for login callback
        hashIndex = pathname.indexOf('bt_login&');
        if(hashIndex > 0) {
          hash = pathname.substring(hashIndex + 9);
        } else {
          return;
        }
      }
      var packet_string;
      var func = null;
      try {
        var hostWindow = window.parent;
        if (hash.indexOf('fname=') == 0) {
          var packetStart = hash.indexOf('&');
          var frame_name = hash.substr(6, packetStart-6);
          if(frame_name == "_opener") {
            hostWindow = hostWindow.opener;
          } else if (frame_name == "_oparen") {
            hostWindow = hostWindow.opener.parent;
          } else if (frame_name != "_parent") {
            hostWindow = hostWindow.frames[frame_name];
          }
          packet_string = hash.substr(packetStart+1);
        } else {
          hostWindow = hostWindow.parent;
          packet_string = hash;
        }
        func = hostWindow.BT.XdComm.onReceiverLoaded;
      } catch (e) {
        if (e.number == -2146828218) {
          //Permission denied
          return;
        }
      }

      if(func) {
        hostWindow.BT.XdComm.onReceiverLoaded(packet_string);
      } else {
          try {
            window.setTimout(BTIntern.XdReceiver.dispatchMessage, 500);
          } catch (e) {
          }
      }
    }
  };
}

if (!BT.Sys) {
	BT.Sys=function(){};
	BT.Sys.isUndefined=function(o){return(o===undefined);}
	BT.Sys.isNullOrUndefined=function(o){return(o===null)||(o===undefined);}
	BT.Sys.isNullOrEmpty=function(s){return!s||!s.length;}
	BT.Sys.parseBool=function(s){return(s.toLowerCase()=='true');}
	BT.Sys.trim=function(s){return s.replace(/^\s*|\s*$/g,'');}
	BT.$create_Point=function (x,y){var $o={};$o.x=x;$o.y=y;return $o;}
	BT.$create_Size=function (w,h){var $o={};$o.w=w;$o.h=h;return $o;}
	BT.Sys.format=function(format){
		BT.Sys.format._formatRE=/(\{[^\}^\{]+\})/g;
		var values=arguments;
		return format.replace(BT.Sys.format._formatRE,function(str,m){var index=parseInt(m.substr(1));var value=values[index+1];if(BT.Sys.isNullOrUndefined(value)){return'';}
		return value.toString();});
	}
}

// Only load if this class is not already loaded
if (!BTIntern.Cookie) {
   BTIntern.Cookie={
	set:function(name,value,path,domain,days){
		if(BT.Sys.isNullOrUndefined(value)){value='';}
		var cookie=name+'='+encodeURIComponent(value)+';';
		if(days){var today=new Date();
		var expire=new Date(today.getTime()+3600000*24*days);
		cookie+='expires='+expire.toUTCString()+';';}
		if(path){cookie+='path='+path+';';}
		if(domain){cookie+='domain='+domain+';';}
		document.cookie=cookie;
	},
	clear:function(name,path,domain){
		BTIntern.Cookie.set(name,'',path,domain,-10);
	},
	getValue:function(name){
		var nameEQ=name+'=';
		var ca=document.cookie.split(';');
		for(var i=0;i<ca.length;i++){
			var c=ca[i];
			c=BT.Sys.trim(c);
			if(!c.indexOf(nameEQ)){
				c=decodeURIComponent(c.substr(nameEQ.length));
				return c;
			}
		}
		return null;
	}
  }
}

if(!BT.Utility){
	BT.Utility={
		get_windowSize:function(){
			var size=BT.$create_Size((window&&window.innerWidth)||(document&&document.documentElement&&document.documentElement.clientWidth)||(document&&document.body&&document.body.clientWidth)||0,(window&&window.innerHeight)||(document&&document.documentElement&&document.documentElement.clientHeight)||(document&&document.body&&document.body.clientHeight)||0);return size;
		},
		get_documentSize:function(){
			var s=BT.$create_Size(document.body.scrollWidth,document.body.scrollHeight);if(s.w<=0){s.w=document.documentElement.scrollWidth;}
			if(s.h<=0){s.h=document.documentElement.scrollHeight;}
			return s;
		},
		get_windowLocation:function(){
			var location=BT.$create_Point(0,0);
			var l,t;if(window.screenLeft){l=window.screenLeft;t=window.screenTop;}else{l=window.screenX;t=window.screenY;}
			location.x=l;location.y=t;;if(BT.Sys.isUndefined(location.x)){location.x=0;}
			if(BT.Sys.isUndefined(location.y)){location.y=0;}
			return location;
        },
		waitForValue:function(evaluateCallback, expectedValue, callback){
			$result=evaluateCallback();
			if($result==expectedValue){callback();
			}else{setTimeout(function(){BT.Utility.waitForValue(evaluateCallback, expectedValue, callback)}, 500);}
		}
	}
}

if (!BT.Orori) {
  // XdReceiver class
  BT.Orori = {
	  _session:false,
	  getLoginStatus:function(){
		 return BT.Orori._session;
	  },
	  init:function(apiKey,xdChannelUrl,callback){
		 if(!apiKey && !xdChannelUrl){return;}
		 BT.XdComm.apiKey=apiKey;
		 BT.XdComm.receiverUrl=xdChannelUrl;	
		 BT.XdComm.refreshQueryStatus();
		 if(typeof(callback)=='function'){
			 BT.Utility.waitForValue(BT.Orori.getLoginStatus,true, callback);
		 }
	  },
	  requireLogin:function(callback){
		 if(this._session){if(callback){callback(null);}}
		 else{
			url=BT.XdComm.createLoginUrl();
			BT.Dialog.showBrowserPopupLogin(url);
			BT.Utility.waitForValue(BT.Orori.getLoginStatus,true, callback);
		 }
	  }
   }
}

if (!BT.Dialog) {
  BT.Dialog={
	loginWindow:null,
	showBrowserPopupLogin:function(url){
	  var windowLocation=BT.Utility.get_windowLocation();
	  var windowSize=BT.Utility.get_windowSize();
	  var popupSize=BT.$create_Size(448,426);
	  var popupScreen=BT.$create_Point(Math.max(0,windowLocation.x+(windowSize.w-popupSize.w)/2),Math.max(0,windowLocation.y+(windowSize.h-popupSize.h)/2));
	  BT.Dialog.loginWindow=window.open(url,'_blank',BT.Sys.format('location=yes,left={0},top={1},width={2},height={3},resizable=yes',popupScreen.x,popupScreen.y,popupSize.w,popupSize.h),true);
	}
  };
}

if (!BT.XdComm) {
  // XdReceiver class
  BT.XdComm = {
	 commServer:http_server_url,
	 commSecureServer:https_server_url, 
     apiKey:null,
	 receiverUrl:null,	
	 session_key:null, 
	 uid:null,
	 expires:null,
	 sig:null,
	 createLoginUrl:function(){
		var url=BT.XdComm.commSecureServer+'login_xd.php';
		var q_params={api_key:BT.XdComm.apiKey,next:BT.XdComm.receiverUrl,host:clientHost,location:clientLocation,guid:Math.random()};
		return BT.XdComm.addQueryParameters(url,BT.XdComm.createQueryString(q_params));
	 },
	 onReceiverLoaded:function(hash){
		var packetStart = hash.indexOf('session=');
		var packetData = hash.substr(packetStart+8);
        var packetSession = decodeURIComponent(packetData);
		var session_params=BT.XdComm.deserialize(packetSession);
		BT.XdComm.session_key=session_params.session_key;
		BT.XdComm.uid=session_params.uid;
		BT.XdComm.expires=session_params.expires;
		BT.XdComm.sig=session_params.sig;
		sessionRecord=({"session_key":BT.XdComm.session_key, "uid":BT.XdComm.uid, "expires":BT.XdComm.expires, "secret":BT.XdComm.sig});
		if(BT.Dialog.loginWindow)BT.Dialog.loginWindow.close();
		BT.XdComm.setSessionCookies(sessionRecord);
	 },
	 setSessionCookies:function(record){
		if(record.secret&&record.session_key){
			BTIntern.Cookie.set(BT.XdComm.apiKey,record.secret,'/','',0);
			BTIntern.Cookie.set(BT.XdComm.apiKey+'_user','','/','',0);
			BTIntern.Cookie.set(BT.XdComm.apiKey+'_sig',record.secret,'/','',0);
			BTIntern.Cookie.set(BT.XdComm.apiKey+'_session_key',record.session_key,'/','',0);
			BTIntern.Cookie.set(BT.XdComm.apiKey+'_expires',-1,'/','',0);
			BT.Orori._session=true;
		}
	 },
	 refreshQueryStatus:function(){
		$null_cookies=({"expires":-1});
		BT.XdComm.setSessionCookies($null_cookies);
		srcUrl=BT.XdComm.commServer+'login_status.php';
		var q_params={api_key:BT.XdComm.apiKey,channel:BT.XdComm.receiverUrl,host:clientHost,location:clientLocation,guid:Math.random()};
		srcUrl=BT.XdComm.addQueryParameters(srcUrl,BT.XdComm.createQueryString(q_params));
		BT.XdComm.createNamedHiddenIFrame('loginStatus',srcUrl,null,null);
	 },
	 deserialize:function(s){
		if(s==''){return null;}
		return eval('('+s+')');
	 },
	 createNamedHiddenIFrame:function(frameName,srcUrl,className,otherAttributes){
	    var divDom=document.createElement('div');
		divDom=BT.XdComm.get_hiddenIFrameContainer();
		if(!className){className='X_SERVER_IFRAME';}
		var iframe_markup='<iframe name=\"'+frameName+'\" ';if(otherAttributes){iframe_markup+=otherAttributes;}
		iframe_markup+=' src=\"'+srcUrl+'\" class=\"'+className+'\" scrolling=\"no\" frameborder=\"0\"></iframe>';
		divDom.innerHTML=iframe_markup;
		iframes = divDom.getElementsByTagName('iframe');
		iframes[0].src=srcUrl;
		return divDom.childNodes[0];
	 },
	 addQueryParameters:function(url,queryParameters){
		if(url.indexOf('?')>0){return url+'&'+queryParameters;}
		else{return url+'?'+queryParameters;}
	 },
	 createQueryString:function(q_params){
		var url='';
		var $dict1=q_params;
		for(var $key2 in $dict1){var param={key:$key2,value:$dict1[$key2]};url+=param.key+'='+encodeURIComponent((param.value))+'&';}
		if(url!==''&&url.charAt(url.length-1)==='&'){url=url.substr(0,url.length-1);}
		return url;
	 },
	 get_hiddenIFrameContainer:function(){
		return document.getElementById('X_HiddenContainer');
	 }
   }
}

