/*
* easyXDM
* http://easyxdm.net/
* Copyright(c) 2009, Øyvind Sean Kinsey, oyvind@kinsey.no.
*
* MIT Licensed - http://easyxdm.net/license/mit.txt
*
*/
(function(window,document,location,setTimeout,decodeURIComponent,encodeURIComponent){var global=this;var _channelId=0;var emptyFn=Function.prototype;var reURI=/^(http.?:\/\/([^\/\s]+))/,reParent=/[\-\w]+\/\.\.\//,reDoubleSlash=/([^:])\/\//g;function isHostMethod(object,property){var t=typeof object[property];return t=="function"||(!!(t=="object"&&object[property]))||t=="unknown"}function isHostObject(object,property){return !!(typeof(object[property])=="object"&&object[property])}var on=(function(){if(isHostMethod(window,"addEventListener")){return function(target,type,listener){target.addEventListener(type,listener,false)}}else{return function(object,sEvent,fpNotify){object.attachEvent("on"+sEvent,fpNotify)}}}());var un=(function(){if(isHostMethod(window,"removeEventListener")){return function(target,type,listener,useCapture){target.removeEventListener(type,listener,useCapture)}}else{return function(object,sEvent,fpNotify){object.detachEvent("on"+sEvent,fpNotify)}}}());function getDomainName(url){return url.match(reURI)[2]}function getLocation(url){return url.match(reURI)[1]}function resolveUrl(url){url=url.replace(reDoubleSlash,"$1/");if(!url.match(/^(http||https):\/\//)){var path=(url.substring(0,1)==="/")?"":location.pathname;if(path.substring(path.length-1)!=="/"){path=path.substring(0,path.lastIndexOf("/")+1)}url=location.protocol+"//"+location.host+path+url}while(reParent.test(url)){url=url.replace(reParent,"")}return url}function appendQueryParameters(url,parameters){var q=[];for(var key in parameters){if(parameters.hasOwnProperty(key)){q.push(key+"="+parameters[key])}}return url+((url.indexOf("?")===-1)?"?":"&")+q.join("&")}var Query=(function(){var query={},pair,search=location.search.substring(1).split("&"),i=search.length;while(i--){pair=search[i].split("=");query[pair[0]]=pair[1]}return query}());function undef(v){return typeof v==="undefined"}function getJSON(){var cached={};var obj={a:[1,2,3]},json='{"a":[1,2,3]}';if(JSON&&typeof JSON.stringify==="function"&&JSON.stringify(obj).replace((/\s/g),"")===json){return JSON}if(Object.toJSON){if(Object.toJSON(obj).replace((/\s/g),"")===json){cached.stringify=Object.toJSON}}if(typeof String.prototype.evalJSON==="function"){obj=json.evalJSON();if(obj.a&&obj.a.length===3&&obj.a[2]===3){cached.parse=function(str){return str.evalJSON()}}}if(cached.stringify&&cached.parse){getJSON=function(){return cached};return cached}return null}function apply(destination,source,noOverwrite){var member;for(var prop in source){if(source.hasOwnProperty(prop)){if(prop in destination){member=source[prop];if(typeof member==="object"){apply(destination[prop],member,noOverwrite)}else{if(!noOverwrite){destination[prop]=source[prop]}}}else{destination[prop]=source[prop]}}}return destination}function createFrame(config){var frame;
/*@cc_on
if (config.props.name){
frame = document.createElement("");
}
@*/
if(!frame){frame=document.createElement("IFRAME")}apply(frame,config.props);frame.id=frame.name;if(config.onLoad){frame.loadFn=function(){config.onLoad(frame.contentWindow)};on(frame,"load",frame.loadFn)}if(config.container){frame.border=frame.frameBorder=0;config.container.appendChild(frame)}else{frame.style.position="absolute";frame.style.left="-2000px";frame.style.top="0px";document.body.appendChild(frame)}return frame}var getXhr=(function(){if(isHostMethod(window,"XMLHttpRequest")){return function(){return new XMLHttpRequest()}}else{var item=(function(){var list=["Microsoft","Msxml2","Msxml3"],i=list.length;while(i--){try{item=list[i]+".XMLHTTP";var obj=new ActiveXObject(item);return item}catch(e){}}}());return function(){return new ActiveXObject(item)}}}());function ajax(config){apply(config,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","X-Requested-With":"XMLHttpRequest"},success:emptyFn,error:function(msg){throw new Error(msg)},data:{},type:"plain"},true);var req=getXhr(),q=[];req.open(config.method,config.url,true);for(var prop in config.headers){if(config.headers.hasOwnProperty(prop)){req.setRequestHeader(prop,config.headers[prop])}}req.onreadystatechange=function(){if(req.readyState==4){if(req.status>=200&&req.status<300){var response=req.responseText;if(config.type==="json"){response=getJSON().parse(response)}config.success(response)}else{config.error("An error occured. Status code: "+req.status)}req.onreadystatechange=null;delete req.onreadystatechange}};for(var key in config.data){if(config.data.hasOwnProperty(key)){q.push(encodeURIComponent(key)+"="+encodeURIComponent(config.data[key]))}}req.send(q.join("&"))}function prepareTransportStack(config){var protocol=config.protocol,stackEls;config.isHost=config.isHost||undef(Query.xdm_p);if(!config.props){config.props={}}if(!config.isHost){config.channel=Query.xdm_c;config.secret=Query.xdm_s;config.remote=decodeURIComponent(Query.xdm_e);protocol=Query.xdm_p}else{config.remote=resolveUrl(config.remote);config.channel=config.channel||"default"+_channelId++;config.secret=Math.random().toString(16).substring(2);if(undef(protocol)){if(isHostMethod(window,"postMessage")){protocol="1"}else{if(isHostMethod(window,"ActiveXObject")&&isHostMethod(window,"execScript")){protocol="3"}else{if(config.remoteHelper){config.remoteHelper=resolveUrl(config.remoteHelper);protocol="2"}else{protocol="0"}}}}}switch(protocol){case"0":apply(config,{interval:300,delay:2000,useResize:true,useParent:false,usePolling:false},true);if(config.isHost){if(!config.local){var domain=location.protocol+"//"+location.host,images=document.body.getElementsByTagName("img"),i=images.length,image;while(i--){image=images[i];if(image.src.substring(0,domain.length)===domain){config.local=image.src;break}}if(!config.local){config.local=window}}var parameters={xdm_c:config.channel,xdm_p:0};if(config.local===window){config.usePolling=true;config.useParent=true;config.local=location.protocol+"//"+location.host+location.pathname+location.search;parameters.xdm_e=encodeURIComponent(config.local);parameters.xdm_pa=1}else{parameters.xdm_e=resolveUrl(config.local)}if(config.container){config.useResize=false;parameters.xdm_po=1}config.remote=appendQueryParameters(config.remote,parameters)}else{apply(config,{channel:Query.xdm_c,remote:decodeURIComponent(Query.xdm_e),useParent:!undef(Query.xdm_pa),usePolling:!undef(Query.xdm_po),useResize:config.useParent?false:config.useResize})}stackEls=[new easyXDM.stack.HashTransport(config),new easyXDM.stack.ReliableBehavior({timeout:((config.useResize?50:config.interval*1.5)+(config.usePolling?config.interval*1.5:50))}),new easyXDM.stack.QueueBehavior({encode:true,maxLength:4000-config.remote.length}),new easyXDM.stack.VerifyBehavior({initiate:config.isHost})];break;case"1":stackEls=[new easyXDM.stack.PostMessageTransport(config)];break;case"2":stackEls=[new easyXDM.stack.NameTransport(config),new easyXDM.stack.QueueBehavior(),new easyXDM.stack.VerifyBehavior({initiate:config.isHost})];break;case"3":stackEls=[new easyXDM.stack.NixTransport(config)];break}return stackEls}function chainStack(stackElements){var stackEl,defaults={incoming:function(message,origin){this.up.incoming(message,origin)},outgoing:function(message,recipient){this.down.outgoing(message,recipient)},callback:function(success){this.up.callback(success)},init:function(){this.down.init()},destroy:function(){this.down.destroy()}};for(var i=0,len=stackElements.length;i<\/script>')}}};(function(){var _map={};easyXDM.Fn={set:function(name,fn){_map[name]=fn},get:function(name,del){var fn=_map[name];if(del){delete _map[name]}return fn}}}());easyXDM.Socket=function(config){var stack=chainStack(prepareTransportStack(config).concat([{incoming:function(message,origin){config.onMessage(message,origin)},callback:function(success){if(config.onReady){config.onReady(success)}}}])),recipient=getLocation(config.remote);this.destroy=function(){stack.destroy()};this.postMessage=function(message){stack.outgoing(message,recipient)};stack.init()};easyXDM.Rpc=function(config,jsonRpcConfig){if(jsonRpcConfig.local){for(var method in jsonRpcConfig.local){if(jsonRpcConfig.local.hasOwnProperty(method)){var member=jsonRpcConfig.local[method];if(typeof member==="function"){jsonRpcConfig.local[method]={method:member}}}}}var stack=chainStack(prepareTransportStack(config).concat([new easyXDM.stack.RpcBehavior(this,jsonRpcConfig),{callback:function(success){if(config.onReady){config.onReady(success)}}}]));this.destroy=function(){stack.destroy()};stack.init()};easyXDM.stack.PostMessageTransport=function(config){var pub,frame,callerWindow,targetOrigin;function _getOrigin(event){if(event.origin){return event.origin}if(event.uri){return getLocation(event.uri)}if(event.domain){return location.protocol+"//"+event.domain}throw"Unable to retrieve the origin of the event"}function _window_onMessage(event){var origin=_getOrigin(event);if(origin==targetOrigin&&event.data.substring(0,config.channel.length+1)==config.channel+" "){pub.up.incoming(event.data.substring(config.channel.length+1),origin)}}return(pub={outgoing:function(message,domain){callerWindow.postMessage(config.channel+" "+message,domain||targetOrigin)},destroy:function(){un(window,"message",_window_onMessage);if(frame){callerWindow=null;frame.parentNode.removeChild(frame);frame=null}},init:function(){targetOrigin=getLocation(config.remote);if(config.isHost){on(window,"message",function waitForReady(event){if(event.data==config.channel+"-ready"){callerWindow=frame.contentWindow;un(window,"message",waitForReady);on(window,"message",_window_onMessage);setTimeout(function(){pub.up.callback(true)},0)}});apply(config.props,{src:appendQueryParameters(config.remote,{xdm_e:location.protocol+"//"+location.host,xdm_c:config.channel,xdm_p:1})});frame=createFrame(config)}else{on(window,"message",_window_onMessage);callerWindow=window.parent;callerWindow.postMessage(config.channel+"-ready",targetOrigin);setTimeout(function(){pub.up.callback(true)},0)}}})};easyXDM.stack.NixTransport=function(config){var pub,frame,send,targetOrigin,proxy;return(pub={outgoing:function(message,domain){send(message)},destroy:function(){proxy=null;if(frame){frame.parentNode.removeChild(frame);frame=null}},init:function(){targetOrigin=getLocation(config.remote);if(config.isHost){try{if(!isHostMethod(window,"GetNixProxy")){window.execScript("Class NixProxy\n Private m_parent, m_child, m_Auth\n\n Public Sub SetParent(obj, auth)\n If isEmpty(m_Auth) Then m_Auth = auth\n SET m_parent = obj\n End Sub\n Public Sub SetChild(obj)\n SET m_child = obj\n m_parent.ready()\n End Sub\n\n Public Sub SendToParent(data, auth)\n If m_Auth = auth Then m_parent.send(CStr(data))\n End Sub\n Public Sub SendToChild(data, auth)\n If m_Auth = auth Then m_child.send(CStr(data))\n End Sub\nEnd Class\nFunction GetNixProxy()\n Set GetNixProxy = New NixProxy\nEnd Function\n","vbscript")}proxy=GetNixProxy();proxy.SetParent({send:function(msg){pub.up.incoming(msg,targetOrigin)},ready:function(){setTimeout(function(){pub.up.callback(true)},0)}},config.secret);send=function(msg){proxy.SendToChild(msg,config.secret)}}catch(e){throw new Error("Could not set up VBScript NixProxy:"+e.message)}apply(config.props,{src:appendQueryParameters(config.remote,{xdm_e:location.protocol+"//"+location.host,xdm_c:config.channel,xdm_s:config.secret,xdm_p:3})});frame=createFrame(config);frame.contentWindow.opener=proxy}else{try{proxy=window.opener}catch(e){throw new Error("Cannot access window.opener")}proxy.SetChild({send:function(msg){global.setTimeout(function(){pub.up.incoming(msg,targetOrigin)},0)}});send=function(msg){proxy.SendToParent(msg,config.secret)};setTimeout(function(){pub.up.callback(true)},0)}}})};easyXDM.stack.NameTransport=function(config){var pub;var isHost,callerWindow,remoteWindow,readyCount,callback,remoteOrigin,remoteUrl;function _sendMessage(message){var url=config.remoteHelper+(isHost?("#_3"+encodeURIComponent(remoteUrl+"#"+config.channel)):("#_2"+config.channel));callerWindow.contentWindow.sendMessage(message,url)}function _onReady(){if(isHost){if(++readyCount===2||!isHost){pub.up.callback(true)}}else{_sendMessage("ready");pub.up.callback(true)}}function _onMessage(message){pub.up.incoming(message,remoteOrigin)}function _onLoad(){if(callback){setTimeout(function(){callback(true)},0)}}return(pub={outgoing:function(message,domain,fn){callback=fn;_sendMessage(message)},destroy:function(){callerWindow.parentNode.removeChild(callerWindow);callerWindow=null;if(isHost){remoteWindow.parentNode.removeChild(remoteWindow);remoteWindow=null}},init:function(){isHost=config.isHost;readyCount=0;remoteOrigin=getLocation(config.remote);config.local=resolveUrl(config.local);if(isHost){easyXDM.Fn.set(config.channel,function(message){if(isHost&&message==="ready"){easyXDM.Fn.set(config.channel,_onMessage);_onReady()}});remoteUrl=appendQueryParameters(config.remote,{xdm_e:config.local,xdm_c:config.channel,xdm_p:2});apply(config.props,{src:remoteUrl+"#"+config.channel,name:config.channel});remoteWindow=createFrame(config)}else{config.remoteHelper=config.remote;easyXDM.Fn.set(config.channel,_onMessage)}callerWindow=createFrame({props:{src:config.local+"#_4"+config.channel},onLoad:function(){un(callerWindow,"load",callerWindow.loadFn);easyXDM.Fn.set(config.channel+"_load",_onLoad);_onReady()}})}})};easyXDM.stack.HashTransport=function(config){var pub;var me=this,isHost,_timer,pollInterval,_lastMsg,_msgNr,_listenerWindow,_callerWindow;var usePolling,useParent,useResize,_remoteOrigin;function _sendMessage(message){if(!_callerWindow){return}var url=config.remote+"#"+(_msgNr++)+"_"+message;if(isHost||!useParent){_callerWindow.contentWindow.location=url;if(useResize){_callerWindow.width=_callerWindow.width>75?50:100}}else{_callerWindow.location=url}}function _handleHash(hash){_lastMsg=hash;pub.up.incoming(_lastMsg.substring(_lastMsg.indexOf("_")+1),_remoteOrigin)}function _onResize(){_handleHash(_listenerWindow.location.hash)}function _pollHash(){if(_listenerWindow.location.hash&&_listenerWindow.location.hash!=_lastMsg){_handleHash(_listenerWindow.location.hash)}}function _attachListeners(){if(usePolling){_timer=setInterval(_pollHash,pollInterval)}else{on(_listenerWindow,"resize",_onResize)}}return(pub={outgoing:function(message,domain){_sendMessage(message)},destroy:function(){if(usePolling){window.clearInterval(_timer)}else{if(_listenerWindow){un(_listenerWindow,"resize",_pollHash)}}if(isHost||!useParent){_callerWindow.parentNode.removeChild(_callerWindow)}_callerWindow=null},init:function(){isHost=config.isHost;pollInterval=config.interval;_lastMsg="#"+config.channel;_msgNr=0;usePolling=config.usePolling;useParent=config.useParent;useResize=config.useResize;_remoteOrigin=getLocation(config.remote);if(!isHost&&useParent){_listenerWindow=window;_callerWindow=parent;_attachListeners();pub.up.callback(true)}else{apply(config,{props:{src:(isHost?config.remote:config.remote+"#"+config.channel),name:(isHost?"local_":"remote_")+config.channel},onLoad:(isHost&&useParent||!isHost)?(function(){_listenerWindow=window;_attachListeners();pub.up.callback(true)}):null});_callerWindow=createFrame(config);if(isHost&&!useParent){var tries=0,max=config.delay/50;(function getRef(){if(++tries>max){throw new Error("Unable to reference listenerwindow")}if(_listenerWindow){return}try{_listenerWindow=_callerWindow.contentWindow.frames["remote_"+config.channel];window.clearTimeout(_timer);_attachListeners();pub.up.callback(true);return}catch(ex){setTimeout(getRef,50)}}())}}}})};easyXDM.stack.ReliableBehavior=function(config){var pub,timer,current,next,sendId=0,sendCount=0,maxTries=config.tries||5,timeout=config.timeout,receiveId=0,callback;return(pub={incoming:function(message,origin){var indexOf=message.indexOf("_"),ack=parseInt(message.substring(0,indexOf),10),id;message=message.substring(indexOf+1);indexOf=message.indexOf("_");id=parseInt(message.substring(0,indexOf),10);indexOf=message.indexOf("_");message=message.substring(indexOf+1);if(timer&&ack===sendId){window.clearTimeout(timer);timer=null;if(callback){setTimeout(function(){callback(true)},0)}}if(id!==0){if(id!==receiveId){receiveId=id;message=message.substring(id.length+1);pub.down.outgoing(id+"_0_ack",origin);setTimeout(function(){pub.up.incoming(message,origin)},config.timeout/2)}else{pub.down.outgoing(id+"_0_ack",origin)}}},outgoing:function(message,origin,fn){callback=fn;sendCount=0;current={data:receiveId+"_"+(++sendId)+"_"+message,origin:origin};(function send(){timer=null;if(++sendCount>maxTries){if(callback){setTimeout(function(){callback(false)},0)}}else{pub.down.outgoing(current.data,current.origin);timer=setTimeout(send,config.timeout)}}())},destroy:function(){if(timer){window.clearInterval(timer)}pub.down.destroy()}})};easyXDM.stack.QueueBehavior=function(config){var pub,queue=[],waiting=false,incoming="",destroying,maxLength=(config)?config.maxLength:0,encode=(config)?(config.encode||false):false;function dispatch(){if(waiting||queue.length===0||destroying){return}waiting=true;var message=queue.shift();pub.down.outgoing(message.data,message.origin,function(success){waiting=false;if(message.callback){setTimeout(function(){message.callback(success)},0)}dispatch()})}return(pub={incoming:function(message,origin){var indexOf=message.indexOf("_"),seq=parseInt(message.substring(0,indexOf),10);incoming+=message.substring(indexOf+1);if(seq===0){if(encode){incoming=decodeURIComponent(incoming)}pub.up.incoming(incoming,origin);incoming=""}},outgoing:function(message,origin,fn){if(encode){message=encodeURIComponent(message)}var fragments=[],fragment;if(maxLength){while(message.length!==0){fragment=message.substring(0,maxLength);message=message.substring(fragment.length);fragments.push(fragment)}}else{fragments.push(message)}while((fragment=fragments.shift())){queue.push({data:fragments.length+"_"+fragment,origin:origin,callback:fragments.length===0?fn:null})}dispatch()},destroy:function(){destroying=true;pub.down.destroy()}})};easyXDM.stack.VerifyBehavior=function(config){var pub,mySecret,theirSecret,verified=false;function startVerification(){mySecret=Math.random().toString(16).substring(2);pub.down.outgoing(mySecret)}return(pub={incoming:function(message,origin){var indexOf=message.indexOf("_");if(indexOf===-1){if(message===mySecret){pub.up.callback(true)}else{if(!theirSecret){theirSecret=message;if(!config.initiate){startVerification()}pub.down.outgoing(message)}}}else{if(message.substring(0,indexOf)===theirSecret){pub.up.incoming(message.substring(indexOf+1),origin)}}},outgoing:function(message,origin,fn){pub.down.outgoing(mySecret+"_"+message,origin,fn)},callback:function(success){if(config.initiate){startVerification()}}})};easyXDM.stack.RpcBehavior=function(proxy,config){var pub,serializer=config.serializer||getJSON();var _callbackCounter=0,_callbacks={};function _send(data){data.jsonrpc="2.0";pub.down.outgoing(serializer.stringify(data))}function _emptyFn(){}function _createMethod(definition,method){var slice=Array.prototype.slice;return function(){var l=arguments.length,callback,message={method:method};if(l>0&&typeof arguments[l-1]==="function"){if(l>1&&typeof arguments[l-2]==="function"){callback={success:arguments[l-2],error:arguments[l-1]};message.params=slice.call(arguments,0,l-2)}else{callback={success:arguments[l-1]};message.params=slice.call(arguments,0,l-1)}_callbacks[""+(++_callbackCounter)]=callback;message.id=_callbackCounter}else{message.params=slice.call(arguments,0)}_send(message)}}function _executeMethod(method,id,fn,params){if(!fn){if(id){_send({id:id,error:{code:-32601,message:"Procedure not found."}})}return}var used=false,success,error;if(id){success=function(result){if(used){return}used=true;_send({id:id,result:result})};error=function(message){if(used){return}used=true;_send({id:id,error:{code:-32099,message:"Application error: "+message}})}}else{success=error=_emptyFn}try{var result=fn.method.apply(fn.scope,params.concat([success,error]));if(!undef(result)){success(result)}}catch(ex1){error(ex1.message)}}return(pub={incoming:function(message,origin){var data=serializer.parse(message);if(data.method){if(config.handle){config.handle(data,_send)}else{_executeMethod(data.method,data.id,config.local[data.method],data.params)}}else{var callback=_callbacks[data.id];if(data.result&&callback.success){callback.success(data.result)}else{if(data.error){if(callback.error){callback.error(data.error)}}}delete _callbacks[data.id]}},init:function(){if(config.remote){for(var method in config.remote){if(config.remote.hasOwnProperty(method)){proxy[method]=_createMethod(config.remote[method],method)}}}pub.down.init()},destroy:function(){for(var method in config.remote){if(config.remote.hasOwnProperty(method)&&proxy.hasOwnProperty(method)){delete proxy[method]}}pub.down.destroy()}})}})(window,document,location,window.setTimeout,decodeURIComponent,encodeURIComponent);