/**
* AJAX Component
*
* @author Absoft AB
* @version 1.00
* @copyright Absoft AB, 24 January, 2007
* @package default
**/
var AJAX = function(parent) {
this.__parent = parent;
this.proxyURL = "/apps/proxy/cpaint2.proxy.php";
this.ajaxobject = new cpaint();
this.ajaxobject.set_debug(-1);
this.ajaxobject.set_transfer_mode('GET');
this.externalCall2 = function(Obj) {
/*
Obj {
method:		(string) post/get
url:		(string) [http://]url
callback:	(string) cbFunction
reference:	(Object) ref
auth:		(Object) {
username:(string)user
password:(string)pass
}
credentials = encode64(username + ":" + password);
headers = ["Authentication", "Basic " + credentials];
}
*/
if (Obj.url.substr(0,4) == "http")
Obj.url = "/apps/proxy/http_post.php?url="+Obj.url;//"proxy.php?url="+encodeURIComponent(Obj.url);
var credentials, headers;
var AjaxObject = {};
var callback = this.__parent.__instance+"."+"modHandler.module('"+Obj.reference.moduleName+"').getModule()."+Obj.callback;
if (Obj.auth) {
credentials = Obj.auth.username + ":" + Obj.auth.password;
headers = ["Authentication", "Basic " + credentials];
}
AjaxObject.method = Obj.method;
AjaxObject.postBody = Obj.postBody;
AjaxObject.onSuccess = function(transport) { try { eval(callback+"(transport)") } catch(e){alert("err..\n"+e)}};
new Ajax.Request(Obj.url,AjaxObject);
/*
new Ajax.Request(Obj.url,
{
method:Obj.method,
postBody:null,
onSuccess: function(transport,json){
rawText = transport.responseText;
json = eval('(' + rawText + ')');
cbSaveEditFileDialogue(json);
alert("got response..");
eval(callback);
}
}
);*/
}
this.externalCall = function() {
Debug.notice("AJAX","externalCall","started");
var a = arguments;
var str = "";
var arglist = new Array();
for (i=2;i<a.length;i++)
arglist[arglist.length] = "a["+i+"]";
var ref = a[0];
var cbPath = "";
if (typeof ref == "object")  {
cbPath = "modHandler.module('"+ref.moduleName+"').getModule().";
}
else if (typeof ref == "string")  {
if (ref.length>0)
ref=ref+".";
cbPath = ref;
}
var callType = a[1];
var relCallback = a[4];
absCallback = this.__parent.__instance+"."+cbPath+relCallback;
var tmpFuncName = "tmpCallback"+(Math.round(Math.random()*100000));
var tmpFuncString = tmpFuncName+" = function(response,txt,data) { "+absCallback+"(response,txt,'"+a[5]+"'); delete "+tmpFuncName+"; }";
eval(tmpFuncString);
arglist[2] = tmpFuncName;
this.ajaxobject.set_response_type(callType);
if (a[2].substr(0,4) == "http")
this.ajaxobject.set_proxy_url(this.proxyURL);
else
this.ajaxobject.set_proxy_url("");
var args = arglist.join(",");
Debug.notice("AJAX","externalCall","sending to backend");
var a = eval("this.ajaxobject.call("+args+");");
}
}
/**
 * Playback component
 *
 * @author Absoft AB
 * @version 1.00
 * @copyright Absoft AB, 24 January, 2007
 * @package default
 **/
var Player = function(parent) {
var windowObjectSeed = Math.round(Math.random()*40000);
this.__parent = parent;
this.handler = null;
this.windowProps = {width:document.documentElement.offsetWidth,height:document.documentElement.offsetHeight};
this.lastWindowProps = {width:null,height:null};
this.config = this.__parent.config.PLAYER;
if (this.__parent.config.GET.volume) {
this.__parent.cookies.saveCookie("volume",this.__parent.config.GET.volume);
}
var videoWinDiv = document.getElementById(this.config.playerWindowId);
var fileTypes = new Array();
var contentTypes = new Array();
this.replaceRules = new Object();
this.getPlayerPath = function() {
}
var wmediaObj = new Object();
wmediaObj.rndName = "WMPlayer_"+windowObjectSeed;
wmediaObj.render = function(file){
mime2 = "application/x-mplayer2";
var WMObj = "<object name=\""+wmediaObj.rndName+"\" width=\""+videoWinDiv.offsetWidth+"\" height=\""+videoWinDiv.offsetHeight+"\" showcontrols=\"false\" CLASSID=\"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6\" ><param name=\"url\" value=\""+file+"\"><param name=\"autoStart\" value=\"true\"><param name=\"ShowControls\" value=\"false\"><param name=\"uiMode\" value=\"none\"><param name=\"ShowDisplay\" value=\"false\"><param name=\"fileName\" value=\""+file+"\"><param name=\"ShowStatusBar\" value=\"false\"><param name=\"wmode\" value=\"transparent\" /><embed width=\""+videoWinDiv.offsetWidth+"\" height=\""+videoWinDiv.offsetHeight+"\" showControls=0 ShowStatusBar=0 src=\""+file+"\" url=\""+file+"\" pluginspage=\"plugin.html\" wmode=\"transparent\"></object>";
videoWinDiv.innerHTML = WMObj;
player_data_maxvolume = 100;
}
wmediaObj.voiden = function(){return 0}
wmediaObj.getPlayedSeconds = function() {
try {
return document[wmediaObj.rndName].controls.currentPosition;
}
catch(e){}
}
wmediaObj.getTotalSeconds = function() {
try {
return document[wmediaObj.rndName].currentMedia.duration;
}
catch(e){}
}
wmediaObj.getMediaEnded = wmediaObj.voiden;
wmediaObj.playstate = wmediaObj.voiden;
wmediaObj.setVolumePct = wmediaObj.voiden;
wmediaObj.getVolumePct = wmediaObj.voiden;
wmediaObj.seek = wmediaObj.voiden;
wmediaObj.getBuffering = wmediaObj.voiden;
var flashObj = new Object();
flashObj.ref = this;
flashObj.rndName = "flashPlayer_"+windowObjectSeed;
flashObj.getPlayedSeconds = function() {
var retVal;
try {
retVal = flashMovie().GetVariable("time_seconds");
}
catch(e) {
}
if (!retVal)
retVal = 0;
this.lastOffset = retVal;
return retVal;
}
flashObj.getTotalSeconds  = function() {
var retVal;
try {
retVal = flashMovie().GetVariable("time_total");
}
catch(e) {
}
return retVal;
}
flashObj.getBuffering = function() {
var retVal;
try {
retVal = flashMovie().GetVariable("mediaBuffering");
}
catch(e) {
retVal = false;
}
return retVal;
}
flashObj.getBufferingPct = function() {
var retVal;
try {
retVal = flashMovie().GetVariable("bufferHealth");
}
catch(e) {
retVal = false;
}
return retVal;
}
flashObj.getMediaEnded = function() {
var retVal;
try {
retVal = flashMovie().GetVariable("mediaFinished");
}
catch(e) {
retVal = 'false';
}
return eval(retVal);
}
flashObj.setPlaystate = function(state) {
try {
flashMovie().SetVariable("CALL.playState",state);
}
catch (e) {
}
}
flashObj.getPlaystate = function() {
var state;
try {
state = flashMovie().GetVariable("pState");
}
catch(e){state="error:"+e}
try {
flashMovie().SetVariable("WINDOWMODE",this.ref.windowState);
flashMovie().SetVariable("DOCHEIGHT",videoWinDiv.offsetHeight);
flashMovie().SetVariable("DOCWIDTH",videoWinDiv.offsetWidth);
}
catch (e) {
}
return state;
}
flashObj.setVolumePct = function(vol) {
this.ref.__parent.modHandler.updateEvent([{name:'media_new_volume',value:vol}]);
flashMovie().SetVariable("soundVolume",vol);
}
flashObj.getVolumePct = function(vol) {
return flashMovie().GetVariable("soundVolume");
}
flashObj.seek = function(secs) {
secs = Math.round(secs);
flashMovie().SetVariable("CALL.seekOffset",secs);
this.ref.__parent.modHandler.updateEvent([
{name:'media_new_offset',value:secs}
]);
}
flashObj.firstTime = true;
flashObj.render = function(file,offset) {
var fileUrl = escape(file.URL);
this.ref.__parent.modHandler.updateEvent([
{name:'media_ended',value:false}
]);
var dataType="";
if (file.type == 'video/flash' || file.type == 'video/x-flv')
dataType = 'flv';
else if (file.type == 'application/x-shockwave-flash')
dataType = 'swf';
else
dataType = 'mp3';
var cookieVolume;
if (this.ref.__parent.config.COOKIE != null && this.ref.__parent.config.COOKIE['volume'] != null)
cookieVolume = this.ref.__parent.config.COOKIE['volume'];
else
cookieVolume = 50;
flashPath = "flash.swf?dataurl="+fileUrl+"&mwidth="+videoWinDiv.offsetWidth+"&mheight="+videoWinDiv.offsetHeight+"&windowMode="+this.ref.windowState+"&mediaVolume="+cookieVolume+"&datatype="+dataType;
if (!isNaN(parseInt(offset)) && offset > 0) {
flashPath +="&offset="+offset;
}
flashPath+="&rnd="+Math.random();
var so = new SWFObject(flashPath, flashObj.rndName, '100%', '100%', "7", "#000000");
so.addParam("scale","exactfit");
so.addParam("allowFullScreen", "true");
so.useExpressInstall("expressinstall.swf");
var g = so.write(this.ref.config.playerWindowId);
var isSVSE = 0;
if (navigator.userAgent) {
isSVSE = navigator.userAgent.indexOf('sv');
}
if (isSVSE<0) {
if (navigator.userLanguage != null)
isSVSE = navigator.userLanguage.indexOf('sv');
}
isSVSE = (isSVSE>=0);
var enStr = 'In order to watch videos on this site, you need Adobe Flash Player. Get it <a href="http://www.adobe.com/go/getflashplayer" target="_blank">here</a>.';
var seStr = 'F&ouml;r att titta p&aring; denna s&auml;ndning m&aring;ste du ha insticksprogrammet Adobe Flash Player installerat. Klicka <a href="http://www.adobe.com/go/getflashplayer" target="_blank">h&auml;r</a> f&ouml;r att h&auml;mta det.';
if(g) {
    var pl = this.ref.__parent.modHandler.module("modTab_playing").getModule().playlistData;
    //var pl = this.ref.__parent.modHandler.module("modPlaylist").getModule().playlistData;
    var randomnumber=Math.floor(Math.random()*11000000);
    var statsURL = "/stat/"+file.priority+".gif?c="+pl.path+"&f="+pl.name+"&r="+randomnumber;
    var statsImg = new Image();
    statsImg.src = statsURL;
}
if (!g) {
var c = $(this.ref.config.playerWindowId);
c.innerHTML = '<div style="padding:30px;font-size:20px;color:#FFFFFF">' + (isSVSE ? seStr : enStr) + '</div>';
if (navigator.appName == 'Microsoft Internet Explorer') {
c.innerHTML += '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+
'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"'+
'WIDTH="1" HEIGHT="1" id="abPlayer"><PARAM NAME=movie VALUE="'+flashPath+'"><PARAM NAME=quality VALUE=high><PARAM NAME=bgcolor '+										'VALUE=#000000><EMBED src="'+flashPath+'" quality=high bgcolor=#FFFFFF WIDTH="1" HEIGHT="1"'+
'NAME="abPlayer" ALIGN="" TYPE="application/x-shockwave-flash"'+
'PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED></OBJECT>';
}
}
}
var interval = null;
this.lastTime = null;
this.monitor = function() {
var updateObj = [];
var updateObj2 = [];
if (this.handler != null) {
var time_played = this.handler.getPlayedSeconds();
var time_total = this.handler.getTotalSeconds();
var media_ended = this.handler.getMediaEnded();
var buffering = this.handler.getBufferingPct();
var play_state = this.handler.getPlaystate();
this.windowProps.width = document.documentElement.offsetWidth;
this.windowProps.height = document.documentElement.offsetHeight
this.__parent.modHandler.updateEvent([{name:'media_ended',value:false}]);
updateObj[updateObj.length] = {name:'window_width',value:this.windowProps.width};
updateObj[updateObj.length] = {name:'window_height',value:this.windowProps.height};
if (this.lastWindowState != this.windowState) {
updateObj[updateObj.length] = {name:'new_window_state',value:this.windowState};
}
updateObj2[updateObj2.length] = {name:'time_played',value:time_played};
updateObj2[updateObj2.length] = {name:'time_total',value:time_total};
updateObj[updateObj.length] = {name:'media_ended',value:media_ended};
updateObj[updateObj.length] = {name:'media_buffering',value:buffering};
updateObj[updateObj.length] = {name:'media_new_playstate',value:play_state};
this.__parent.config.saveQuery('offset',time_played);
this.lastWindowState = this.windowState;
this.__parent.modHandler.updateEvent(updateObj);
this.__parent.modHandler.updateEvent(updateObj2,true);
}
}
function addContentType(types,name) {
for (i=0;i<types.length;i++)
contentTypes[types[i]] = name;
}
function addFileType(types,name) {
for (i=0;i<types.length;i++) {
fileTypes[types[i]] = name;
}
}
this.getHandler = function(type) {
return contentTypes[type] ? contentTypes[type] : null;
}
this.monitorObject = null;
this.monitoring = function(cond) {
if (cond) {
this.monitorObject = setInterval(this.__parent.__instance+'.player.monitor()',1000);
}
else {
clearInterval(this.monitorObject);
}
}
this.init = function() {
this.monitoring(true);
}
this.setReplaceRule = function(from,to) {
this.replaceRules[from] = to;
}
this.applyReplaceRules = function(f) {
var from;
var to;
var _file = f;
for(ruleName in this.replaceRules) {
from = ruleName;
to = this.replaceRules[ruleName];
f.replace(from,to);
}
if (_file == undefined)
_file = f;
return _file;
}
this.setFile = function(file,fileoffset) {
file.URL = this.applyReplaceRules(file.URL);
file.URL = unescape(file.URL);
file.URL = file.URL.replace(/#Random#/gi,Math.round(Math.random()*100000000));
var handler = this.getHandler(file.type);
this.handler = handler;
this.__parent.modHandler.updateEvent([{name:'media_ended',value:false}]);
if (handler == undefined) {
this.__parent.modHandler.updateEvent([{name:'unknown_file_type',value:file}],true);
}
else {
this.handler.lastFile = file;
this.__parent.modHandler.updateEvent([{name:'playing_media_url',value:file.URL}],true);
if (this.passedOffset != null) {
this.handler.lastOffset = this.passedOffset;
this.handler.render(file,this.passedOffset);
this.passedOffset = null;
}
else {
if (fileoffset)
this.handler.render(file,fileoffset);
else
this.handler.render(file);
}
}
delete data;
delete fileExt;
delete file;
}
this.playMedia = function() {
if (this.handler)
this.handler.setPlaystate(1);
else
this.__parent.modHandler.updateEvent([{name:'no_handler',value:Math.random()}]);
}
this.pauseMedia = function() {
if (this.handler)
this.handler.setPlaystate(0);
else
this.__parent.modHandler.updateEvent([{name:'no_handler',value:Math.random()}]);
}
function flashMovie() {
var ua = navigator.userAgent.toLowerCase();
var winObj;
if (ua.indexOf("msie") != -1) {
winObj =  window[flashObj.rndName];
}
else if (ua.indexOf("firefox") != -1){
winObj =  document[flashObj.rndName];
}
else {
winObj =  document[flashObj.rndName];
}
if (winObj == undefined)
return;
else
return winObj;
}
this.windowState = 'normal';
this.lastWindowState = 'normal';
this.toggleFullscreen = function() {
if (this.windowState == 'normal')
this.windowState = 'fullscreen'
else
this.windowState = 'normal';
this.renderScreen();
}
this.renderScreen = function() {
}
this.reRenderCurrent = function() {
this.handler.render(this.handler.lastFile,this.handler.lastOffset);
}
addContentType(['video/flash','audio/mp3','audio/mpeg','video/x-flv'],flashObj);
addFileType(['flv','mp3','mp3-stream','swf'],flashObj);
addFileType(['wmv','avi','wma'],wmediaObj);
}
/**
* Player base component
*
* @author Absoft AB
* @version 1.00
* @copyright Absoft AB, 24 January, 2007
* @package default
**/
function AbPlayer(__instance, __config, __baseURL, __passedQuery,__debug) {
if (__instance == null)
__instance = "abPlayer";
if (__config == null)
__config = "default";
if (__baseURL == null)
__baseURL = "";
this.__instance = __instance;
this.__config = __config;
this.__baseURL = __baseURL;
this.__passedQuery = __passedQuery;
this.tmpPlayerRef = null;
this.modHandler = null;
this.player = null;
this.controls = null;
this.init = function() {
this.ajax = new AJAX(this);
this.config = new ConfigReader(this, this.__passedQuery);
this.cookies = new Cookies(this);
this.config.init();
}
this.createObjects = function() {
this.player = new Player(this);
this.modHandler = new ModHandler(this);
if (!this.moduleFilesLoaded) {
this.layoutLoader = new Layout.loader(this);
}
this.loadModules();
}
var compColl = new Toolbox.componentCollection();
compColl.addComponent("player");
compColl.addComponent("modHandler");
compColl.addComponent("AJAX");
compColl.addComponent("layout");
compColl.addComponent("configReader");
compColl.addComponent("cookies");
compColl.addExternalComponent("drag","Drag");
compColl.addExternalComponent("swfobject","SWFObject");
compColl.addExternalComponent("cpaint","cpaint");
compColl.addExternalComponent("effects","Effect");
Toolbox.loadComponents(compColl.getComponentList(),this.__instance+".init()",this.__baseURL);
this.loadModules = function() {
var modules = Toolbox.array.clone(this.config.CORE.loadModules);
Toolbox.loadModules(modules,this.__instance+".readModuleFiles()",this.__baseURL);
}
this.loadedModuleFiles = null;
this.totalModuleFiles = null;
this.readModuleFiles = function() {
var modules = Toolbox.array.clone(this.config.CORE.loadModules);
this.moduleLayoutFilePaths = new Array();
this.moduleTemplateFilePaths = new Array();
for (var i=0;i<modules.length;i++) {
var moduleTemplateFiles = (this.config[modules[i]] && this.config[modules[i]].templateFiles) ? this.config[modules[i]].templateFiles : null;
var moduleLayoutFiles = (this.config[modules[i]] && this.config[modules[i]].layoutFiles) ? this.config[modules[i]].layoutFiles : null;
if (moduleLayoutFiles != null) {
for (var k=0;k<moduleLayoutFiles.length;k++) {
this.moduleLayoutFilePaths[this.moduleLayoutFilePaths.length] = {name:modules[i],path:this.__baseURL+"templates/"+modules[i]+"/"+moduleLayoutFiles[k]};
}
}
if (moduleTemplateFiles != null) {
for (var k=0;k<moduleTemplateFiles.length;k++) {
this.moduleTemplateFilePaths[this.moduleTemplateFilePaths.length] = {name:modules[i],path:this.__baseURL+"templates/"+modules[i]+"/"+moduleTemplateFiles[k]};
}
}
}
this.moduleFilesCount = 0;
this.moduleFilesTotal = this.moduleLayoutFilePaths.length+this.moduleTemplateFilePaths.length;
this.moduleFilesLeft =  this.moduleLayoutFilePaths.length+this.moduleTemplateFilePaths.length;
if (!this.moduleFilesLoaded) {
this.layoutLoader.loadModuleFiles(this.moduleTemplateFilePaths,this.moduleLayoutFilePaths);
}
else {
this.initPlayer();
}
}
this.moduleFilesLoaded = false;
this.initPlayer = function() {
this.moduleFilesLoaded = true;
Toolbox.removeLoadingScreen();
this.player.init();
this.modHandler.init();
}
}
/**
* Configuration reader component
*
* @author Absoft AB
* @version 1.00
* @copyright Absoft AB, 24 January, 2007
* @package default
**/
function ConfigReader(parent,passedQuery) {
this.__parent = parent;
this.configDir = this.__parent.__baseURL+"config/";
this.init = function() {
this.readQuery();
this.readCookie();
this.setDefaultParams();
this.readConfig(this.__parent.__config);
}
this.setDefaultParams = function() {
var setVol = this.GET['volume'];
if (setVol == undefined && this.COOKIE['volume'] == undefined)
setVol = 50;
else
setVol = this.COOKIE['volume'];
this.COOKIE['volume'] = setVol;
this.__parent.cookies.saveCookie('volume',setVol);
}
this.readQuery = function() {
this.GET = {};
var index = document.URL.indexOf('?');
if ( index != -1 ) {
var nameValuePairs=document.URL.substring(index+1,document.URL.length).split('&');
for ( var i=0; i<nameValuePairs.length; i++ ) {
nameVal = nameValuePairs[i].split('=');
this.GET[nameVal[0]] = unescape(nameVal[1]);
}
}
if (passedQuery) {
for (name in passedQuery)
this.GET[name] = passedQuery[name];
}
}
this.saveQuery = function(name,value) {
this.GET[name] = value;
return value;
}
this.getQuery = function(q) {
if (q)
return this.GET[q];
else
return this.GET;
}
this.getQuerystring = function() {
var r=[];
for (name in this.GET)
r[r.length] = name+"="+this.GET[name];
r=r.join('&');
return r;
}
this.readCookie = function() {
this.COOKIE = {};
if (document.cookie.length > 0) {
var nameValuePairs=document.cookie.split(';');
for ( var i=0; i<nameValuePairs.length; i++ ) {
nameVal = nameValuePairs[i].split('=');
this.COOKIE[nameVal[0]] = unescape(nameVal[1]);
}
}
}
this.readConfig = function(configName) {
var configFile = this.configDir+configName+".ini";
this.CORE = {};
this.CORE.lang = "sv"
this.CORE.enabled = true
this.CORE.loadModules = ["modLiveStream","modControls","modBanner","modTabList","modMediaList","modBandwidthTest","modTab_playing","modTab_tipFriend","modTabs"]
this.CORE.playback = "continuous"
this.PLAYER = {};
this.PLAYER.playerWindowId = "PlayerWindow"
this.PLAYER.playerControlsId = "Controls"
this.PLAYER.playerProgressBarId = "playerProgressBar"
this.PLAYER.playerVolumeId = "playerVolumeContainer"
this.PLAYER.playerStateId = "playerPlayPauseContainer"
this.PLAYER.playerOpenFullscreenId = "playerFullscreen"
this.PLAYER.playerCloseFullscreenId = "playerCloseFullscreen"
this.modBanner = {};
this.modBanner.layoutFiles = ["modBanner.lo"]
this.modTabList = {};
this.modTabList.tabListContainer = "FolderList"
this.modTabList.startPath = "oatv.abcdn.net"
this.modTabList.playerFolderId = "modFolderList"
this.modTabList.layoutFiles = ["modTabList.lo"]
this.modTabList.templateFiles = ["modTabList.xml"]
this.modMediaList = {};
this.modMediaList.playerMediaId = "MediaList"
this.modMediaList.layoutFiles = ["modMediaList.lo"]
this.modMediaList.templateFiles = ["modMediaList.xml"]
this.modMediaList.activeTypes = ["fsx","flv","pls","mp3"]
this.modMediaList.skipFilter = /.*350k.*/
this.modTabs = {};
this.modTabs.tabPrefix = "modTab_"
this.modTabs.tabContainerId = "TabHead"
this.modTabs.tabContentId = "TabContent"
this.modTabs.layoutFiles = ["modTabs.lo"]
this.modTabs.templateFiles = ["modTabs.xml"]
this.modControls = {};
this.modControls.playerControlsContainerId = "Controls"
this.modControls.playerProgressbarId = "playerProgressBar"
this.modControls.playerProgressbarHandleId = "playerHandle"
this.modControls.playerVolumeContainerId = "playerVolumeContainer"
this.modControls.playerVolumeHandleId = "playerVolumeHandle"
this.modControls.playerVolumeBarId = "playerVolumeBar"
this.modControls.playerVolumePlusId = "volPlus"
this.modControls.playerVolumeMinusId = "volMinus"
this.modControls.playerBufferTextId = "buffering"
this.modControls.playerTimeId = "playerTime"
this.modControls.playerDataContainerId = "playerDataContainer"
this.modControls.playerFullscreenContainerId = "playerFullscreen"
this.modControls.playerCloseFullscreenContainerId = "playerCloseFullscreen"
this.modControls.playerPlayPauseContainerId = "playerPlayPauseContainer"
this.modControls.playerHasPlayPause = "yes"
this.modControls.playerHasProgressbar = "yes"
this.modControls.playerHasVolumebar = "yes"
this.modControls.playerCanSkip = "no"
this.modControls.timeMode = 0
this.modControls.showTotal = true
this.modControls.layoutFiles = ["modControls.lo"]
this.modControls.templateFiles = ["modControls.xml"]
this.modBandwidthTest = {};
this.modBandwidthTest.playerBandwidthContainerId = "bwContainer"
this.modBandwidthTest.defaultBitrate = 750;
this.modBandwidthTest.fallbackBitrate = 350;
this.modBandwidthTest.testFileSize = 101896;
this.modTab_playing = {};
this.modTab_playing.layoutFiles = ["modTab_playing.lo"]
this.modTab_playing.templateFiles = ["modTab_playing.xml"]
this.modTab_tipFriend = {};
this.modTab_tipFriend.layoutFiles = ["modTab_tipFriend.lo"]
this.modTab_tipFriend.templateFiles = ["modTab_tipFriend.xml"]
this.modTab_tipFriend.backendURL = "http://allehanda_api:api123@mktvtest.adeprimo.se/frontend_dev.php/api/rest/player/tipfriend"
this.cbLoadConfig("\n");
}
this.cbLoadConfig = function(response, txt) {
var lines = response.split("\n");
var category = null;
for(var i=0; i<lines.length; i++) {
var line = lines[i];
if (line == "") continue;
if (line.substr(0,1) == ";") continue;
if (line.substr(0,1) == "[") {
category = line.substring(1,line.indexOf("]"));
this[category] = {};
} else {
var parts = line.split("=");
if (parts[1] == undefined) {
continue;
}
var key = Toolbox.string.trim(parts[0]);
var value = eval(Toolbox.string.trim(parts[1]));
if (category != null)
this[category][key] = value;
else
this[key] = value;
}
}
this.__parent.createObjects();
}
}
/**
* Cookie writing component.
*
* @author Absoft AB
* @version 1.00
* @copyright Absoft AB, 24 January, 2007
* @package default
**/
var Cookies = function(parent) {
this.__parent = parent;
this.saveCookie = function(name,value) {
this.__parent.config.COOKIE[name] = value;
}
}
var Debug = new Object();
Debug.debugLevel = 2;
Debug.output = function(str,type) {
var win = window.open("debug.html","debug");
win.window.writeDebug("gay");
}
Debug.error	= function(str) { // 1
if (Debug.debugLevel >= 1)
Debug.output(str,"error");
}
Debug.notice = function(str) { // 3
if (Debug.debugLevel >= 3)
Debug.output(str,"notice");
}
Debug.warning = function(str) { // 2
if (Debug.debugLevel >= 2)
Debug.output(str,"warning");
}
/**
* Layout managing component
*
* @author Absoft AB
* @version 1.00
* @copyright Absoft AB, 24 January, 2007
* @package default
**/
var Layout = function() {};
Layout.loader = function(parent) {
this.__parent = parent;
Layout.templates = {};
Layout.layouts = {};
this.loadModuleFiles = function(templateList,layoutList) {
this.templateList = templateList;
this.layoutList = layoutList;
this.templateLength = templateList.length;
this.layoutLength = layoutList.length;
this.totalFileLength = templateList.length+layoutList.length;
this.filesLoaded = 0;
this.loadModuleTemplates(templateList);
}
this.getTempFromString = function(temp) {
var file = temp.path.split("/")[2];
var xmlstr = templates[temp.name][file];
if (xmlstr != null) {
if (window.ActiveXObject) {
var doc=new ActiveXObject("Microsoft.XMLDOM");
doc.async="false";
doc.loadXML(xmlstr);
}
else {
var parser=new DOMParser();
var doc=parser.parseFromString(xmlstr,"text/xml");
}
this.cbLoadModuleTemplateFile(doc,xmlstr,temp.name);
}
}
this.getLayoutFromString = function(layout) {
var file = layout.path.split("/")[2];
if (layouts[layout.name] != null) {
var lostr = layouts[layout.name][file];
this.cbLoadModuleLayout(lostr,lostr,layout.name);
}
}
this.loadModuleTemplates = function() {
var templateList = this.templateList;
for (var i=0;i<templateList.length;i++) {
this.getTempFromString(templateList[i]);
}
}
this.cbLoadModuleTemplateFile = function(response,txt,module) {
this.filesLoaded++;
if (!Layout.templates[module])
Layout.templates[module] = {};
var rootindex = (response.childNodes.length-1);
var templist = response.childNodes[rootindex];
var temp = templist.firstChild;
while(temp != null) {
if (temp.nodeType == 1) {
var tempName = temp.getAttribute("name");
var tempHTML = temp.childNodes[0].childNodes[0].nodeValue;
Layout.templates[module][tempName] = tempHTML;
}
temp = temp.nextSibling;
}
if (this.filesLoaded == this.templateLength)
this.loadModuleLayouts();
} // END this.cbLoadModuleTemplateFile
this.loadModuleLayouts = function() {
var layoutList = this.layoutList;
for (var i=0;i<layoutList.length;i++) {
this.getLayoutFromString(layoutList[i]);
}
}
this.cbLoadModuleLayout = function(response,txt,module) {
this.filesLoaded++;
Layout.layouts[module] = response;
if (this.totalFileLength == this.filesLoaded) {
this.__parent.initPlayer();
}
}
this.initLayout = function(module) {
try {
eval(Layout.layouts[module]);
}
catch (e) {
}
}
}
Layout.manager = function(modRef,totalFiles) {
Debug.notice("LayoutManager","class","instantiated");
this.module = modRef;
this.totalFiles = totalFiles;
this.fileCount = 0;
this.init = function() {
Debug.notice("LayoutManager","init","started");
var layouts = Layout.layouts[this.module.moduleName];
eval(layouts);
Debug.notice("LayoutManager","init","finished");
}
this.runTemplate = function(tempName) {
Debug.notice("LayoutManager","runTemplate","started ["+tempName+"]");
try {
var temp = Layout.templates[this.module.moduleName][tempName];
} catch(e) {
Debug.error("LayoutManager","runTemplate",tempName+": "+e);
}
var product = this.fillTemplate(temp);
Debug.notice("LayoutManager","runTemplate","finished ["+tempName+"]");
return product;
}
this.output = function(data, container) {
Debug.notice("LayoutManager","output","started ["+container+"]");
var cobj = document.getElementById(container);
if (cobj == null) return false;
cobj.innerHTML = data;
Debug.notice("LayoutManager","output","finished ["+container+"]");
return true;
}
this.replace = function(element,template) {
var parent = element.parentNode;
if (!element.id)
element.id = "div_"+Math.round(Math.random()*100000);
var elementId = element.id;
var tmpDiv = document.createElement('div');
tmpDiv.innerHTML = template;
for (var i=0;i<parent.childNodes.length;i++) {
if (parent.childNodes[i].id == elementId) {
parent.replaceChild(tmpDiv,parent.childNodes[i]);
}
}
}
this.fillTemplate = function(str) {
Debug.notice("LayoutManager","fillTemplate","started");
if (!str)
return "";
var re = /\<\<([^<]+)\>\>/gi;
var matches = str.match(re);
var match = "";
try {
matches.length;
} catch (e) {
return str;
}
for(var i=0;i<matches.length;i++) {
match = matches[i];
if (typeof match != "string") continue;
var cleanmatch = match.replace("<<","").replace(">>","");
if (cleanmatch == "#") {
var product = this.module.__parent.__instance+".modHandler.module('"+this.module.moduleName+"').getModule()";
} else if (cleanmatch == "@") {
var product = this.module.__parent.__instance;
} else if (cleanmatch == "$") {
var product = this.module.__parent.__instance+".modHandler.module('"+this.module.moduleName+"').getModule().lm";
}
else {
var product = eval(cleanmatch);
}
str = str.replace(match, product);
}
str = Toolbox.string.trim(str);
Debug.notice("LayoutManager","fillTemplate","finished");
return str;
}
this.getURL = function(src) {
var dir = "images/";
var url = this.module.__parent.__baseURL+dir+this.module.moduleName+"/"+src;
return url;
}
}
/**
* Module handling component
*
* @author Absoft AB
* @version 1.00
* @copyright Absoft AB, 24 January, 2007
* @package default
**/
var ModHandler = function(parent) {
var _modules = [];
this.__parent = parent;
var _subscriptions = [];
this.events = new Object();
this.init = function() {
var loadModules = this.__parent.config.CORE.loadModules;
_modules = [];
var initedModules = this.initModules(loadModules);
if (initedModules.inited != loadModules.length) {
this.writeError(initedModules.failed + " kunde inte laddas");
}
}
this.writeError = function(error) {
try {
if (this.__parent.config.CORE.devmode) {
}
}catch (e) {
}
}
this.initModules = function(loadModules) {
var inited = 0;
var failed = [];
if (typeof loadModules == "object") {
for(var i = 0; i < loadModules.length; i++) {
var modName = loadModules[i];
if (this.createModule(modName)) {
inited++;
try {
this.module(modName).init();
}
catch (e) {
this.writeError(modName +" kunde ej initieras.");
}
}
else {
failed[failed.length] = modName;
}
}
}
return {inited:inited,failed:failed}
}
this.createModule = function(modName) {
var tmpInstance;
try { tmpInstance = eval("new "+modName+"(this.__parent)"); } catch(nothing){alert(nothing)};
if (tmpInstance)
this.registerModule(tmpInstance,modName);
else
this.writeError(modName + " could not be inited. Missing module file.")
return (tmpInstance != undefined);
}
this.registerModule = function(moduleInstance,moduleName) {
_modules[moduleName] = moduleInstance;
_modules[moduleName].moduleName = moduleName;
if (this.__parent.config[moduleName]) {
moduleInstance.config = this.__parent.config[moduleName];
}
moduleInstance.updateEvent = this.__parent.modHandler.updateEvent;
}
this.initModule = function(moduleName) {
_modules[moduleName].init();
}
this.getModule = function(moduleName) {
return _modules[moduleName];
}
this.module = function(moduleName) {
var modName = moduleName;
var me = this;
return {
getModule:function() {
return _modules[modName];
}
,
unsubscribe:function(priority,eventArray) {
var update = new Array();
for (i=0;i<eventArray.length;i++) {
try {
update[update.length] = {name:eventArray[i],value:me.events[eventArray[i]]};
delete _subscriptions[eventArray[i]] [_subscriptions[eventArray[i]].length-1 ][modName];
}
catch(nothing) {
}
var list = 0;
for (mod in _subscriptions[eventArray[i]][_subscriptions[eventArray[i]].length-1]) {
if (_modules[mod] && _modules[mod].eventReceiver != undefined)
list++;
}
if (list == 0) {
_subscriptions[eventArray[i]].splice(_subscriptions[eventArray[i]].length-1,1);
}
}
me.rebroadCastEvent(update);
return update;
}
,
subscribe:function(priority,eventArray) {
var update = new Array();
for (i=0;i<eventArray.length;i++) {
if (_subscriptions[eventArray[i]] == undefined)
_subscriptions[eventArray[i]] = new Array();
if (_subscriptions[eventArray[i]][priority] == undefined)
_subscriptions[eventArray[i]][priority] = new Array();
_subscriptions[eventArray[i]][priority][modName] = true;
update = me.createUpdatedEventList({name:eventArray[i],value:me.events[eventArray[i]]},update);
}
me.sendEventList(update);
}
,
init:function() {
_modules[modName].init();
}
};
}
this.rebroadCastEvent = function(eventObj) {
this.updateEvent(eventObj,true);
}
this.updateEvent = function(eventObj,skipCheck) {
var updateThis = new Array();
for (i=0;i<eventObj.length;i++) {
if (!skipCheck) {
if (this.events[eventObj[i].name] == eventObj[i].value) {
continue;
}
else {
}
}
this.events[eventObj[i].name] = eventObj[i].value;
var mName = eventObj[i].name;
if (_subscriptions[mName] != undefined) {
updateThis = this.createUpdatedEventList(eventObj[i],updateThis,skipCheck);
}
}
this.sendEventList(updateThis);
}
this.sendEventList = function(eventlist) {
for (k in eventlist) {
if (typeof eventlist[k] != 'function' && this.module(k).getModule().eventReceiver) {
try {
this.module(k).getModule().eventReceiver(eventlist[k]);
}
catch(e) {
}
}
}
}
this.createUpdatedEventList = function(eventObj,update,skipCheck) {
if (!update)
update = new Array();
var priodepth = _subscriptions[eventObj.name].length-1;
for (var module in _subscriptions[eventObj.name][priodepth]) {
if (update[module] == undefined)
update[module] = new Array();
update[module][eventObj.name] = eventObj.value;
}
return update;
}
}
var parameterHandler = function(parent) {
this.__parent = parent;
this.init = function() {
}
this.parameterCollection = {};
this.addParameter = function(module,obj) {
for (props in obj) {
if (!this.parameterCollection[module])
this.parameterCollection[module] = {};
this.parameterCollection[module][props] = obj[props];
}
}
}
/*  Prototype JavaScript framework, version 1.5.0
*  (c) 2005-2007 Sam Stephenson
*
*  Prototype is freely distributable under the terms of an MIT-style license.
*  For details, see the Prototype web site: http://prototype.conio.net/
*
/*--------------------------------------------------------------------------*/
var Prototype = {
Version: '1.5.0',
BrowserFeatures: {
XPath: !!document.evaluate
},
ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
emptyFunction: function() {},
K: function(x) { return x }
}
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
var Abstract = new Object();
Object.extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
Object.extend(Object, {
inspect: function(object) {
try {
if (object === undefined) return 'undefined';
if (object === null) return 'null';
return object.inspect ? object.inspect() : object.toString();
} catch (e) {
if (e instanceof RangeError) return '...';
throw e;
}
},
keys: function(object) {
var keys = [];
for (var property in object)
keys.push(property);
return keys;
},
values: function(object) {
var values = [];
for (var property in object)
values.push(object[property]);
return values;
},
clone: function(object) {
return Object.extend({}, object);
}
});
Function.prototype.bind = function() {
var __method = this, args = $A(arguments), object = args.shift();
return function() {
return __method.apply(object, args.concat($A(arguments)));
}
}
Function.prototype.bindAsEventListener = function(object) {
var __method = this, args = $A(arguments), object = args.shift();
return function(event) {
return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
}
}
Object.extend(Number.prototype, {
toColorPart: function() {
var digits = this.toString(16);
if (this < 16) return '0' + digits;
return digits;
},
succ: function() {
return this + 1;
},
times: function(iterator) {
$R(0, this, true).each(iterator);
return this;
}
});
var Try = {
these: function() {
var returnValue;
for (var i = 0, length = arguments.length; i < length; i++) {
var lambda = arguments[i];
try {
returnValue = lambda();
break;
} catch (e) {}
}
return returnValue;
}
}
/*--------------------------------------------------------------------------*/
var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
initialize: function(callback, frequency) {
this.callback = callback;
this.frequency = frequency;
this.currentlyExecuting = false;
this.registerCallback();
},
registerCallback: function() {
this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
},
stop: function() {
if (!this.timer) return;
clearInterval(this.timer);
this.timer = null;
},
onTimerEvent: function() {
if (!this.currentlyExecuting) {
try {
this.currentlyExecuting = true;
this.callback(this);
} finally {
this.currentlyExecuting = false;
}
}
}
}
String.interpret = function(value){
return value == null ? '' : String(value);
}
Object.extend(String.prototype, {
gsub: function(pattern, replacement) {
var result = '', source = this, match;
replacement = arguments.callee.prepareReplacement(replacement);
while (source.length > 0) {
if (match = source.match(pattern)) {
result += source.slice(0, match.index);
result += String.interpret(replacement(match));
source  = source.slice(match.index + match[0].length);
} else {
result += source, source = '';
}
}
return result;
},
sub: function(pattern, replacement, count) {
replacement = this.gsub.prepareReplacement(replacement);
count = count === undefined ? 1 : count;
return this.gsub(pattern, function(match) {
if (--count < 0) return match[0];
return replacement(match);
});
},
scan: function(pattern, iterator) {
this.gsub(pattern, iterator);
return this;
},
truncate: function(length, truncation) {
length = length || 30;
truncation = truncation === undefined ? '...' : truncation;
return this.length > length ?
this.slice(0, length - truncation.length) + truncation : this;
},
strip: function() {
return this.replace(/^\s+/, '').replace(/\s+$/, '');
},
stripTags: function() {
return this.replace(/<\/?[^>]+>/gi, '');
},
stripScripts: function() {
return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
},
extractScripts: function() {
var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
return (this.match(matchAll) || []).map(function(scriptTag) {
return (scriptTag.match(matchOne) || ['', ''])[1];
});
},
evalScripts: function() {
return this.extractScripts().map(function(script) { return eval(script) });
},
escapeHTML: function() {
var div = document.createElement('div');
var text = document.createTextNode(this);
div.appendChild(text);
return div.innerHTML;
},
unescapeHTML: function() {
var div = document.createElement('div');
div.innerHTML = this.stripTags();
return div.childNodes[0] ? (div.childNodes.length > 1 ?
$A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) :
div.childNodes[0].nodeValue) : '';
},
toQueryParams: function(separator) {
var match = this.strip().match(/([^?#]*)(#.*)?$/);
if (!match) return {};
return match[1].split(separator || '&').inject({}, function(hash, pair) {
if ((pair = pair.split('='))[0]) {
var name = decodeURIComponent(pair[0]);
var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;
if (hash[name] !== undefined) {
if (hash[name].constructor != Array)
hash[name] = [hash[name]];
if (value) hash[name].push(value);
}
else hash[name] = value;
}
return hash;
});
},
toArray: function() {
return this.split('');
},
succ: function() {
return this.slice(0, this.length - 1) +
String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
},
camelize: function() {
var parts = this.split('-'), len = parts.length;
if (len == 1) return parts[0];
var camelized = this.charAt(0) == '-'
? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
: parts[0];
for (var i = 1; i < len; i++)
camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
return camelized;
},
capitalize: function(){
return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
},
underscore: function() {
return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
},
dasherize: function() {
return this.gsub(/_/,'-');
},
inspect: function(useDoubleQuotes) {
var escapedString = this.replace(/\\/g, '\\\\');
if (useDoubleQuotes)
return '"' + escapedString.replace(/"/g, '\\"') + '"';
else
return "'" + escapedString.replace(/'/g, '\\\'') + "'";
}
});
String.prototype.gsub.prepareReplacement = function(replacement) {
if (typeof replacement == 'function') return replacement;
var template = new Template(replacement);
return function(match) { return template.evaluate(match) };
}
String.prototype.parseQuery = String.prototype.toQueryParams;
var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
initialize: function(template, pattern) {
this.template = template.toString();
this.pattern  = pattern || Template.Pattern;
},
evaluate: function(object) {
return this.template.gsub(this.pattern, function(match) {
var before = match[1];
if (before == '\\') return match[2];
return before + String.interpret(object[match[3]]);
});
}
}
var $break    = new Object();
var $continue = new Object();
var Enumerable = {
each: function(iterator) {
var index = 0;
try {
this._each(function(value) {
try {
iterator(value, index++);
} catch (e) {
if (e != $continue) throw e;
}
});
} catch (e) {
if (e != $break) throw e;
}
return this;
},
eachSlice: function(number, iterator) {
var index = -number, slices = [], array = this.toArray();
while ((index += number) < array.length)
slices.push(array.slice(index, index+number));
return slices.map(iterator);
},
all: function(iterator) {
var result = true;
this.each(function(value, index) {
result = result && !!(iterator || Prototype.K)(value, index);
if (!result) throw $break;
});
return result;
},
any: function(iterator) {
var result = false;
this.each(function(value, index) {
if (result = !!(iterator || Prototype.K)(value, index))
throw $break;
});
return result;
},
collect: function(iterator) {
var results = [];
this.each(function(value, index) {
results.push((iterator || Prototype.K)(value, index));
});
return results;
},
detect: function(iterator) {
var result;
this.each(function(value, index) {
if (iterator(value, index)) {
result = value;
throw $break;
}
});
return result;
},
findAll: function(iterator) {
var results = [];
this.each(function(value, index) {
if (iterator(value, index))
results.push(value);
});
return results;
},
grep: function(pattern, iterator) {
var results = [];
this.each(function(value, index) {
var stringValue = value.toString();
if (stringValue.match(pattern))
results.push((iterator || Prototype.K)(value, index));
})
return results;
},
include: function(object) {
var found = false;
this.each(function(value) {
if (value == object) {
found = true;
throw $break;
}
});
return found;
},
inGroupsOf: function(number, fillWith) {
fillWith = fillWith === undefined ? null : fillWith;
return this.eachSlice(number, function(slice) {
while(slice.length < number) slice.push(fillWith);
return slice;
});
},
inject: function(memo, iterator) {
this.each(function(value, index) {
memo = iterator(memo, value, index);
});
return memo;
},
invoke: function(method) {
var args = $A(arguments).slice(1);
return this.map(function(value) {
return value[method].apply(value, args);
});
},
max: function(iterator) {
var result;
this.each(function(value, index) {
value = (iterator || Prototype.K)(value, index);
if (result == undefined || value >= result)
result = value;
});
return result;
},
min: function(iterator) {
var result;
this.each(function(value, index) {
value = (iterator || Prototype.K)(value, index);
if (result == undefined || value < result)
result = value;
});
return result;
},
partition: function(iterator) {
var trues = [], falses = [];
this.each(function(value, index) {
((iterator || Prototype.K)(value, index) ?
trues : falses).push(value);
});
return [trues, falses];
},
pluck: function(property) {
var results = [];
this.each(function(value, index) {
results.push(value[property]);
});
return results;
},
reject: function(iterator) {
var results = [];
this.each(function(value, index) {
if (!iterator(value, index))
results.push(value);
});
return results;
},
sortBy: function(iterator) {
return this.map(function(value, index) {
return {value: value, criteria: iterator(value, index)};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}).pluck('value');
},
toArray: function() {
return this.map();
},
zip: function() {
var iterator = Prototype.K, args = $A(arguments);
if (typeof args.last() == 'function')
iterator = args.pop();
var collections = [this].concat(args).map($A);
return this.map(function(value, index) {
return iterator(collections.pluck(index));
});
},
size: function() {
return this.toArray().length;
},
inspect: function() {
return '#<Enumerable:' + this.toArray().inspect() + '>';
}
}
Object.extend(Enumerable, {
map:     Enumerable.collect,
find:    Enumerable.detect,
select:  Enumerable.findAll,
member:  Enumerable.include,
entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
if (!iterable) return [];
if (iterable.toArray) {
return iterable.toArray();
} else {
var results = [];
for (var i = 0, length = iterable.length; i < length; i++)
results.push(iterable[i]);
return results;
}
}
Object.extend(Array.prototype, Enumerable);
if (!Array.prototype._reverse)
Array.prototype._reverse = Array.prototype.reverse;
Object.extend(Array.prototype, {
_each: function(iterator) {
for (var i = 0, length = this.length; i < length; i++)
iterator(this[i]);
},
clear: function() {
this.length = 0;
return this;
},
first: function() {
return this[0];
},
last: function() {
return this[this.length - 1];
},
compact: function() {
return this.select(function(value) {
return value != null;
});
},
flatten: function() {
return this.inject([], function(array, value) {
return array.concat(value && value.constructor == Array ?
value.flatten() : [value]);
});
},
without: function() {
var values = $A(arguments);
return this.select(function(value) {
return !values.include(value);
});
},
indexOf: function(object) {
for (var i = 0, length = this.length; i < length; i++)
if (this[i] == object) return i;
return -1;
},
reverse: function(inline) {
return (inline !== false ? this : this.toArray())._reverse();
},
reduce: function() {
return this.length > 1 ? this : this[0];
},
uniq: function() {
return this.inject([], function(array, value) {
return array.include(value) ? array : array.concat([value]);
});
},
clone: function() {
return [].concat(this);
},
size: function() {
return this.length;
},
inspect: function() {
return '[' + this.map(Object.inspect).join(', ') + ']';
}
});
Array.prototype.toArray = Array.prototype.clone;
function $w(string){
string = string.strip();
return string ? string.split(/\s+/) : [];
}
if(window.opera){
Array.prototype.concat = function(){
var array = [];
for(var i = 0, length = this.length; i < length; i++) array.push(this[i]);
for(var i = 0, length = arguments.length; i < length; i++) {
if(arguments[i].constructor == Array) {
for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
array.push(arguments[i][j]);
} else {
array.push(arguments[i]);
}
}
return array;
}
}
var Hash = function(obj) {
Object.extend(this, obj || {});
};
Object.extend(Hash, {
toQueryString: function(obj) {
var parts = [];
this.prototype._each.call(obj, function(pair) {
if (!pair.key) return;
if (pair.value && pair.value.constructor == Array) {
var values = pair.value.compact();
if (values.length < 2) pair.value = values.reduce();
else {
key = encodeURIComponent(pair.key);
values.each(function(value) {
value = value != undefined ? encodeURIComponent(value) : '';
parts.push(key + '=' + encodeURIComponent(value));
});
return;
}
}
if (pair.value == undefined) pair[1] = '';
parts.push(pair.map(encodeURIComponent).join('='));
});
return parts.join('&');
}
});
Object.extend(Hash.prototype, Enumerable);
Object.extend(Hash.prototype, {
_each: function(iterator) {
for (var key in this) {
var value = this[key];
if (value && value == Hash.prototype[key]) continue;
var pair = [key, value];
pair.key = key;
pair.value = value;
iterator(pair);
}
},
keys: function() {
return this.pluck('key');
},
values: function() {
return this.pluck('value');
},
merge: function(hash) {
return $H(hash).inject(this, function(mergedHash, pair) {
mergedHash[pair.key] = pair.value;
return mergedHash;
});
},
remove: function() {
var result;
for(var i = 0, length = arguments.length; i < length; i++) {
var value = this[arguments[i]];
if (value !== undefined){
if (result === undefined) result = value;
else {
if (result.constructor != Array) result = [result];
result.push(value)
}
}
delete this[arguments[i]];
}
return result;
},
toQueryString: function() {
return Hash.toQueryString(this);
},
inspect: function() {
return '#<Hash:{' + this.map(function(pair) {
return pair.map(Object.inspect).join(': ');
}).join(', ') + '}>';
}
});
function $H(object) {
if (object && object.constructor == Hash) return object;
return new Hash(object);
};
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
initialize: function(start, end, exclusive) {
this.start = start;
this.end = end;
this.exclusive = exclusive;
},
_each: function(iterator) {
var value = this.start;
while (this.include(value)) {
iterator(value);
value = value.succ();
}
},
include: function(value) {
if (value < this.start)
return false;
if (this.exclusive)
return value < this.end;
return value <= this.end;
}
});
var $R = function(start, end, exclusive) {
return new ObjectRange(start, end, exclusive);
}
var Ajax = {
getTransport: function() {
return Try.these(
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject('Msxml2.XMLHTTP')},
function() {return new ActiveXObject('Microsoft.XMLHTTP')}
) || false;
},
activeRequestCount: 0
}
Ajax.Responders = {
responders: [],
_each: function(iterator) {
this.responders._each(iterator);
},
register: function(responder) {
if (!this.include(responder))
this.responders.push(responder);
},
unregister: function(responder) {
this.responders = this.responders.without(responder);
},
dispatch: function(callback, request, transport, json) {
this.each(function(responder) {
if (typeof responder[callback] == 'function') {
try {
responder[callback].apply(responder, [request, transport, json]);
} catch (e) {}
}
});
}
};
Object.extend(Ajax.Responders, Enumerable);
Ajax.Responders.register({
onCreate: function() {
Ajax.activeRequestCount++;
},
onComplete: function() {
Ajax.activeRequestCount--;
}
});
Ajax.Base = function() {};
Ajax.Base.prototype = {
setOptions: function(options) {
this.options = {
method:       'post',
asynchronous: true,
contentType:  'application/x-www-form-urlencoded',
encoding:     'UTF-8',
parameters:   ''
}
Object.extend(this.options, options || {});
this.options.method = this.options.method.toLowerCase();
if (typeof this.options.parameters == 'string')
this.options.parameters = this.options.parameters.toQueryParams();
}
}
Ajax.Request = Class.create();
Ajax.Request.Events =
['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
_complete: false,
initialize: function(url, options) {
this.transport = Ajax.getTransport();
this.setOptions(options);
this.request(url);
},
request: function(url) {
this.url = url;
this.method = this.options.method;
var params = this.options.parameters;
if (!['get', 'post'].include(this.method)) {
params['_method'] = this.method;
this.method = 'post';
}
params = Hash.toQueryString(params);
if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_='
if (this.method == 'get' && params)
this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params;
try {
Ajax.Responders.dispatch('onCreate', this, this.transport);
this.transport.open(this.method.toUpperCase(), this.url,
this.options.asynchronous);
if (this.options.asynchronous)
setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);
this.transport.onreadystatechange = this.onStateChange.bind(this);
this.setRequestHeaders();
var body = this.method == 'post' ? (this.options.postBody || params) : null;
this.transport.send(body);
/* Force Firefox to handle ready state 4 for synchronous requests */
if (!this.options.asynchronous && this.transport.overrideMimeType)
this.onStateChange();
}
catch (e) {
this.dispatchException(e);
}
},
onStateChange: function() {
var readyState = this.transport.readyState;
if (readyState > 1 && !((readyState == 4) && this._complete))
this.respondToReadyState(this.transport.readyState);
},
setRequestHeaders: function() {
var headers = {
'X-Requested-With': 'XMLHttpRequest',
'X-Prototype-Version': Prototype.Version,
'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
};
if (this.method == 'post') {
headers['Content-type'] = this.options.contentType +
(this.options.encoding ? '; charset=' + this.options.encoding : '');
/* Force "Connection: close" for older Mozilla browsers to work
* around a bug where XMLHttpRequest sends an incorrect
* Content-length header. See Mozilla Bugzilla #246651.
*/
if (this.transport.overrideMimeType &&
(navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
headers['Connection'] = 'close';
}
if (typeof this.options.requestHeaders == 'object') {
var extras = this.options.requestHeaders;
if (typeof extras.push == 'function')
for (var i = 0, length = extras.length; i < length; i += 2)
headers[extras[i]] = extras[i+1];
else
$H(extras).each(function(pair) { headers[pair.key] = pair.value });
}
for (var name in headers)
this.transport.setRequestHeader(name, headers[name]);
},
success: function() {
return !this.transport.status
|| (this.transport.status >= 200 && this.transport.status < 300);
},
respondToReadyState: function(readyState) {
var state = Ajax.Request.Events[readyState];
var transport = this.transport, json = this.evalJSON();
if (state == 'Complete') {
try {
this._complete = true;
(this.options['on' + this.transport.status]
|| this.options['on' + (this.success() ? 'Success' : 'Failure')]
|| Prototype.emptyFunction)(transport, json);
} catch (e) {
this.dispatchException(e);
}
if ((this.getHeader('Content-type') || 'text/javascript').strip().
match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
this.evalResponse();
}
try {
(this.options['on' + state] || Prototype.emptyFunction)(transport, json);
Ajax.Responders.dispatch('on' + state, this, transport, json);
} catch (e) {
this.dispatchException(e);
}
if (state == 'Complete') {
this.transport.onreadystatechange = Prototype.emptyFunction;
}
},
getHeader: function(name) {
try {
return this.transport.getResponseHeader(name);
} catch (e) { return null }
},
evalJSON: function() {
try {
var json = this.getHeader('X-JSON');
return json ? eval('(' + json + ')') : null;
} catch (e) { return null }
},
evalResponse: function() {
try {
return eval(this.transport.responseText);
} catch (e) {
this.dispatchException(e);
}
},
dispatchException: function(exception) {
(this.options.onException || Prototype.emptyFunction)(this, exception);
Ajax.Responders.dispatch('onException', this, exception);
}
});
Ajax.Updater = Class.create();
Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
initialize: function(container, url, options) {
this.container = {
success: (container.success || container),
failure: (container.failure || (container.success ? null : container))
}
this.transport = Ajax.getTransport();
this.setOptions(options);
var onComplete = this.options.onComplete || Prototype.emptyFunction;
this.options.onComplete = (function(transport, param) {
this.updateContent();
onComplete(transport, param);
}).bind(this);
this.request(url);
},
updateContent: function() {
var receiver = this.container[this.success() ? 'success' : 'failure'];
var response = this.transport.responseText;
if (!this.options.evalScripts) response = response.stripScripts();
if (receiver = $(receiver)) {
if (this.options.insertion)
new this.options.insertion(receiver, response);
else
receiver.update(response);
}
if (this.success()) {
if (this.onComplete)
setTimeout(this.onComplete.bind(this), 10);
}
}
});
Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
initialize: function(container, url, options) {
this.setOptions(options);
this.onComplete = this.options.onComplete;
this.frequency = (this.options.frequency || 2);
this.decay = (this.options.decay || 1);
this.updater = {};
this.container = container;
this.url = url;
this.start();
},
start: function() {
this.options.onComplete = this.updateComplete.bind(this);
this.onTimerEvent();
},
stop: function() {
this.updater.options.onComplete = undefined;
clearTimeout(this.timer);
(this.onComplete || Prototype.emptyFunction).apply(this, arguments);
},
updateComplete: function(request) {
if (this.options.decay) {
this.decay = (request.responseText == this.lastText ?
this.decay * this.options.decay : 1);
this.lastText = request.responseText;
}
this.timer = setTimeout(this.onTimerEvent.bind(this),
this.decay * this.frequency * 1000);
},
onTimerEvent: function() {
this.updater = new Ajax.Updater(this.container, this.url, this.options);
}
});
function $(element) {
if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i < length; i++)
elements.push($(arguments[i]));
return elements;
}
if (typeof element == 'string')
element = document.getElementById(element);
return Element.extend(element);
}
if (Prototype.BrowserFeatures.XPath) {
document._getElementsByXPath = function(expression, parentElement) {
var results = [];
var query = document.evaluate(expression, $(parentElement) || document,
null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0, length = query.snapshotLength; i < length; i++)
results.push(query.snapshotItem(i));
return results;
};
}
document.getElementsByClassName = function(className, parentElement) {
if (Prototype.BrowserFeatures.XPath) {
var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
return document._getElementsByXPath(q, parentElement);
} else {
var children = ($(parentElement) || document.body).getElementsByTagName('*');
var elements = [], child;
for (var i = 0, length = children.length; i < length; i++) {
child = children[i];
if (Element.hasClassName(child, className))
elements.push(Element.extend(child));
}
return elements;
}
};
/*--------------------------------------------------------------------------*/
if (!window.Element)
var Element = new Object();
Element.extend = function(element) {
if (!element || _nativeExtensions || element.nodeType == 3) return element;
if (!element._extended && element.tagName && element != window) {
var methods = Object.clone(Element.Methods), cache = Element.extend.cache;
if (element.tagName == 'FORM')
Object.extend(methods, Form.Methods);
if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
Object.extend(methods, Form.Element.Methods);
Object.extend(methods, Element.Methods.Simulated);
for (var property in methods) {
var value = methods[property];
if (typeof value == 'function' && !(property in element))
element[property] = cache.findOrStore(value);
}
}
element._extended = true;
return element;
};
Element.extend.cache = {
findOrStore: function(value) {
return this[value] = this[value] || function() {
return value.apply(null, [this].concat($A(arguments)));
}
}
};
Element.Methods = {
visible: function(element) {
return $(element).style.display != 'none';
},
toggle: function(element) {
element = $(element);
Element[Element.visible(element) ? 'hide' : 'show'](element);
return element;
},
hide: function(element) {
$(element).style.display = 'none';
return element;
},
show: function(element) {
$(element).style.display = '';
return element;
},
remove: function(element) {
element = $(element);
element.parentNode.removeChild(element);
return element;
},
update: function(element, html) {
html = typeof html == 'undefined' ? '' : html.toString();
$(element).innerHTML = html.stripScripts();
setTimeout(function() {html.evalScripts()}, 10);
return element;
},
replace: function(element, html) {
element = $(element);
html = typeof html == 'undefined' ? '' : html.toString();
if (element.outerHTML) {
element.outerHTML = html.stripScripts();
} else {
var range = element.ownerDocument.createRange();
range.selectNodeContents(element);
element.parentNode.replaceChild(
range.createContextualFragment(html.stripScripts()), element);
}
setTimeout(function() {html.evalScripts()}, 10);
return element;
},
inspect: function(element) {
element = $(element);
var result = '<' + element.tagName.toLowerCase();
$H({'id': 'id', 'className': 'class'}).each(function(pair) {
var property = pair.first(), attribute = pair.last();
var value = (element[property] || '').toString();
if (value) result += ' ' + attribute + '=' + value.inspect(true);
});
return result + '>';
},
recursivelyCollect: function(element, property) {
element = $(element);
var elements = [];
while (element = element[property])
if (element.nodeType == 1)
elements.push(Element.extend(element));
return elements;
},
ancestors: function(element) {
return $(element).recursivelyCollect('parentNode');
},
descendants: function(element) {
return $A($(element).getElementsByTagName('*'));
},
immediateDescendants: function(element) {
if (!(element = $(element).firstChild)) return [];
while (element && element.nodeType != 1) element = element.nextSibling;
if (element) return [element].concat($(element).nextSiblings());
return [];
},
previousSiblings: function(element) {
return $(element).recursivelyCollect('previousSibling');
},
nextSiblings: function(element) {
return $(element).recursivelyCollect('nextSibling');
},
siblings: function(element) {
element = $(element);
return element.previousSiblings().reverse().concat(element.nextSiblings());
},
match: function(element, selector) {
if (typeof selector == 'string')
selector = new Selector(selector);
return selector.match($(element));
},
up: function(element, expression, index) {
return Selector.findElement($(element).ancestors(), expression, index);
},
down: function(element, expression, index) {
return Selector.findElement($(element).descendants(), expression, index);
},
previous: function(element, expression, index) {
return Selector.findElement($(element).previousSiblings(), expression, index);
},
next: function(element, expression, index) {
return Selector.findElement($(element).nextSiblings(), expression, index);
},
getElementsBySelector: function() {
var args = $A(arguments), element = $(args.shift());
return Selector.findChildElements(element, args);
},
getElementsByClassName: function(element, className) {
return document.getElementsByClassName(className, element);
},
readAttribute: function(element, name) {
element = $(element);
if (document.all && !window.opera) {
var t = Element._attributeTranslations;
if (t.values[name]) return t.values[name](element, name);
if (t.names[name])  name = t.names[name];
var attribute = element.attributes[name];
if(attribute) return attribute.nodeValue;
}
return element.getAttribute(name);
},
getHeight: function(element) {
return $(element).getDimensions().height;
},
getWidth: function(element) {
return $(element).getDimensions().width;
},
classNames: function(element) {
return new Element.ClassNames(element);
},
hasClassName: function(element, className) {
if (!(element = $(element))) return;
var elementClassName = element.className;
if (elementClassName.length == 0) return false;
if (elementClassName == className ||
elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
return true;
return false;
},
addClassName: function(element, className) {
if (!(element = $(element))) return;
Element.classNames(element).add(className);
return element;
},
removeClassName: function(element, className) {
if (!(element = $(element))) return;
Element.classNames(element).remove(className);
return element;
},
toggleClassName: function(element, className) {
if (!(element = $(element))) return;
Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
return element;
},
observe: function() {
Event.observe.apply(Event, arguments);
return $A(arguments).first();
},
stopObserving: function() {
Event.stopObserving.apply(Event, arguments);
return $A(arguments).first();
},
cleanWhitespace: function(element) {
element = $(element);
var node = element.firstChild;
while (node) {
var nextNode = node.nextSibling;
if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
element.removeChild(node);
node = nextNode;
}
return element;
},
empty: function(element) {
return $(element).innerHTML.match(/^\s*$/);
},
descendantOf: function(element, ancestor) {
element = $(element), ancestor = $(ancestor);
while (element = element.parentNode)
if (element == ancestor) return true;
return false;
},
scrollTo: function(element) {
element = $(element);
var pos = Position.cumulativeOffset(element);
window.scrollTo(pos[0], pos[1]);
return element;
},
getStyle: function(element, style) {
element = $(element);
if (['float','cssFloat'].include(style))
style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat');
style = style.camelize();
var value = element.style[style];
if (!value) {
if (document.defaultView && document.defaultView.getComputedStyle) {
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css[style] : null;
} else if (element.currentStyle) {
value = element.currentStyle[style];
}
}
if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none'))
value = element['offset'+style.capitalize()] + 'px';
if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
if (Element.getStyle(element, 'position') == 'static') value = 'auto';
if(style == 'opacity') {
if(value) return parseFloat(value);
if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
if(value[1]) return parseFloat(value[1]) / 100;
return 1.0;
}
return value == 'auto' ? null : value;
},
setStyle: function(element, style) {
element = $(element);
for (var name in style) {
var value = style[name];
if(name == 'opacity') {
if (value == 1) {
value = (/Gecko/.test(navigator.userAgent) &&
!/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0;
if(/MSIE/.test(navigator.userAgent) && !window.opera)
element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
} else if(value === '') {
if(/MSIE/.test(navigator.userAgent) && !window.opera)
element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
} else {
if(value < 0.00001) value = 0;
if(/MSIE/.test(navigator.userAgent) && !window.opera)
element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') +
'alpha(opacity='+value*100+')';
}
} else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat';
element.style[name.camelize()] = value;
}
return element;
},
getDimensions: function(element) {
element = $(element);
var display = $(element).getStyle('display');
if (display != 'none' && display != null) // Safari bug
return {width: element.offsetWidth, height: element.offsetHeight};
var els = element.style;
var originalVisibility = els.visibility;
var originalPosition = els.position;
var originalDisplay = els.display;
els.visibility = 'hidden';
els.position = 'absolute';
els.display = 'block';
var originalWidth = element.clientWidth;
var originalHeight = element.clientHeight;
els.display = originalDisplay;
els.position = originalPosition;
els.visibility = originalVisibility;
return {width: originalWidth, height: originalHeight};
},
makePositioned: function(element) {
element = $(element);
var pos = Element.getStyle(element, 'position');
if (pos == 'static' || !pos) {
element._madePositioned = true;
element.style.position = 'relative';
if (window.opera) {
element.style.top = 0;
element.style.left = 0;
}
}
return element;
},
undoPositioned: function(element) {
element = $(element);
if (element._madePositioned) {
element._madePositioned = undefined;
element.style.position =
element.style.top =
element.style.left =
element.style.bottom =
element.style.right = '';
}
return element;
},
makeClipping: function(element) {
element = $(element);
if (element._overflow) return element;
element._overflow = element.style.overflow || 'auto';
if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
element.style.overflow = 'hidden';
return element;
},
undoClipping: function(element) {
element = $(element);
if (!element._overflow) return element;
element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
element._overflow = null;
return element;
}
};
Object.extend(Element.Methods, {childOf: Element.Methods.descendantOf});
Element._attributeTranslations = {};
Element._attributeTranslations.names = {
colspan:   "colSpan",
rowspan:   "rowSpan",
valign:    "vAlign",
datetime:  "dateTime",
accesskey: "accessKey",
tabindex:  "tabIndex",
enctype:   "encType",
maxlength: "maxLength",
readonly:  "readOnly",
longdesc:  "longDesc"
};
Element._attributeTranslations.values = {
_getAttr: function(element, attribute) {
return element.getAttribute(attribute, 2);
},
_flag: function(element, attribute) {
return $(element).hasAttribute(attribute) ? attribute : null;
},
style: function(element) {
return element.style.cssText.toLowerCase();
},
title: function(element) {
var node = element.getAttributeNode('title');
return node.specified ? node.nodeValue : null;
}
};
Object.extend(Element._attributeTranslations.values, {
href: Element._attributeTranslations.values._getAttr,
src:  Element._attributeTranslations.values._getAttr,
disabled: Element._attributeTranslations.values._flag,
checked:  Element._attributeTranslations.values._flag,
readonly: Element._attributeTranslations.values._flag,
multiple: Element._attributeTranslations.values._flag
});
Element.Methods.Simulated = {
hasAttribute: function(element, attribute) {
var t = Element._attributeTranslations;
attribute = t.names[attribute] || attribute;
return $(element).getAttributeNode(attribute).specified;
}
};
if (document.all && !window.opera){
Element.Methods.update = function(element, html) {
element = $(element);
html = typeof html == 'undefined' ? '' : html.toString();
var tagName = element.tagName.toUpperCase();
if (['THEAD','TBODY','TR','TD'].include(tagName)) {
var div = document.createElement('div');
switch (tagName) {
case 'THEAD':
case 'TBODY':
div.innerHTML = '<table><tbody>' +  html.stripScripts() + '</tbody></table>';
depth = 2;
break;
case 'TR':
div.innerHTML = '<table><tbody><tr>' +  html.stripScripts() + '</tr></tbody></table>';
depth = 3;
break;
case 'TD':
div.innerHTML = '<table><tbody><tr><td>' +  html.stripScripts() + '</td></tr></tbody></table>';
depth = 4;
}
$A(element.childNodes).each(function(node){
element.removeChild(node)
});
depth.times(function(){ div = div.firstChild });
$A(div.childNodes).each(
function(node){ element.appendChild(node) });
} else {
element.innerHTML = html.stripScripts();
}
setTimeout(function() {html.evalScripts()}, 10);
return element;
}
};
Object.extend(Element, Element.Methods);
var _nativeExtensions = false;
if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
var className = 'HTML' + tag + 'Element';
if(window[className]) return;
var klass = window[className] = {};
klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
});
Element.addMethods = function(methods) {
Object.extend(Element.Methods, methods || {});
function copy(methods, destination, onlyIfAbsent) {
onlyIfAbsent = onlyIfAbsent || false;
var cache = Element.extend.cache;
for (var property in methods) {
var value = methods[property];
if (!onlyIfAbsent || !(property in destination))
destination[property] = cache.findOrStore(value);
}
}
if (typeof HTMLElement != 'undefined') {
copy(Element.Methods, HTMLElement.prototype);
copy(Element.Methods.Simulated, HTMLElement.prototype, true);
copy(Form.Methods, HTMLFormElement.prototype);
[HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
copy(Form.Element.Methods, klass.prototype);
});
_nativeExtensions = true;
}
}
var Toggle = new Object();
Toggle.display = Element.toggle;
/*--------------------------------------------------------------------------*/
Abstract.Insertion = function(adjacency) {
this.adjacency = adjacency;
}
Abstract.Insertion.prototype = {
initialize: function(element, content) {
this.element = $(element);
this.content = content.stripScripts();
if (this.adjacency && this.element.insertAdjacentHTML) {
try {
this.element.insertAdjacentHTML(this.adjacency, this.content);
} catch (e) {
var tagName = this.element.tagName.toUpperCase();
if (['TBODY', 'TR'].include(tagName)) {
this.insertContent(this.contentFromAnonymousTable());
} else {
throw e;
}
}
} else {
this.range = this.element.ownerDocument.createRange();
if (this.initializeRange) this.initializeRange();
this.insertContent([this.range.createContextualFragment(this.content)]);
}
setTimeout(function() {content.evalScripts()}, 10);
},
contentFromAnonymousTable: function() {
var div = document.createElement('div');
div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
return $A(div.childNodes[0].childNodes[0].childNodes);
}
}
var Insertion = new Object();
Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
initializeRange: function() {
this.range.setStartBefore(this.element);
},
insertContent: function(fragments) {
fragments.each((function(fragment) {
this.element.parentNode.insertBefore(fragment, this.element);
}).bind(this));
}
});
Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
initializeRange: function() {
this.range.selectNodeContents(this.element);
this.range.collapse(true);
},
insertContent: function(fragments) {
fragments.reverse(false).each((function(fragment) {
this.element.insertBefore(fragment, this.element.firstChild);
}).bind(this));
}
});
Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
initializeRange: function() {
this.range.selectNodeContents(this.element);
this.range.collapse(this.element);
},
insertContent: function(fragments) {
fragments.each((function(fragment) {
this.element.appendChild(fragment);
}).bind(this));
}
});
Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
initializeRange: function() {
this.range.setStartAfter(this.element);
},
insertContent: function(fragments) {
fragments.each((function(fragment) {
this.element.parentNode.insertBefore(fragment,
this.element.nextSibling);
}).bind(this));
}
});
/*--------------------------------------------------------------------------*/
Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
initialize: function(element) {
this.element = $(element);
},
_each: function(iterator) {
this.element.className.split(/\s+/).select(function(name) {
return name.length > 0;
})._each(iterator);
},
set: function(className) {
this.element.className = className;
},
add: function(classNameToAdd) {
if (this.include(classNameToAdd)) return;
this.set($A(this).concat(classNameToAdd).join(' '));
},
remove: function(classNameToRemove) {
if (!this.include(classNameToRemove)) return;
this.set($A(this).without(classNameToRemove).join(' '));
},
toString: function() {
return $A(this).join(' ');
}
};
Object.extend(Element.ClassNames.prototype, Enumerable);
var Selector = Class.create();
Selector.prototype = {
initialize: function(expression) {
this.params = {classNames: []};
this.expression = expression.toString().strip();
this.parseExpression();
this.compileMatcher();
},
parseExpression: function() {
function abort(message) { throw 'Parse error in selector: ' + message; }
if (this.expression == '')  abort('empty expression');
var params = this.params, expr = this.expression, match, modifier, clause, rest;
while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
params.attributes = params.attributes || [];
params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''});
expr = match[1];
}
if (expr == '*') return this.params.wildcard = true;
while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) {
modifier = match[1], clause = match[2], rest = match[3];
switch (modifier) {
case '#':       params.id = clause; break;
case '.':       params.classNames.push(clause); break;
case '':
case undefined: params.tagName = clause.toUpperCase(); break;
default:        abort(expr.inspect());
}
expr = rest;
}
if (expr.length > 0) abort(expr.inspect());
},
buildMatchExpression: function() {
var params = this.params, conditions = [], clause;
if (params.wildcard)
conditions.push('true');
if (clause = params.id)
conditions.push('element.readAttribute("id") == ' + clause.inspect());
if (clause = params.tagName)
conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
if ((clause = params.classNames).length > 0)
for (var i = 0, length = clause.length; i < length; i++)
conditions.push('element.hasClassName(' + clause[i].inspect() + ')');
if (clause = params.attributes) {
clause.each(function(attribute) {
var value = 'element.readAttribute(' + attribute.name.inspect() + ')';
var splitValueBy = function(delimiter) {
return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
}
switch (attribute.operator) {
case '=':       conditions.push(value + ' == ' + attribute.value.inspect()); break;
case '~=':      conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break;
case '|=':      conditions.push(
splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect()
); break;
case '!=':      conditions.push(value + ' != ' + attribute.value.inspect()); break;
case '':
case undefined: conditions.push('element.hasAttribute(' + attribute.name.inspect() + ')'); break;
default:        throw 'Unknown operator ' + attribute.operator + ' in selector';
}
});
}
return conditions.join(' && ');
},
compileMatcher: function() {
this.match = new Function('element', 'if (!element.tagName) return false; \
element = $(element); \
return ' + this.buildMatchExpression());
},
findElements: function(scope) {
var element;
if (element = $(this.params.id))
if (this.match(element))
if (!scope || Element.childOf(element, scope))
return [element];
scope = (scope || document).getElementsByTagName(this.params.tagName || '*');
var results = [];
for (var i = 0, length = scope.length; i < length; i++)
if (this.match(element = scope[i]))
results.push(Element.extend(element));
return results;
},
toString: function() {
return this.expression;
}
}
Object.extend(Selector, {
matchElements: function(elements, expression) {
var selector = new Selector(expression);
return elements.select(selector.match.bind(selector)).map(Element.extend);
},
findElement: function(elements, expression, index) {
if (typeof expression == 'number') index = expression, expression = false;
return Selector.matchElements(elements, expression || '*')[index || 0];
},
findChildElements: function(element, expressions) {
return expressions.map(function(expression) {
return expression.match(/[^\s"]+(?:"[^"]*"[^\s"]+)*/g).inject([null], function(results, expr) {
var selector = new Selector(expr);
return results.inject([], function(elements, result) {
return elements.concat(selector.findElements(result || element));
});
});
}).flatten();
}
});
function $$() {
return Selector.findChildElements(document, $A(arguments));
}
var Form = {
reset: function(form) {
$(form).reset();
return form;
},
serializeElements: function(elements, getHash) {
var data = elements.inject({}, function(result, element) {
if (!element.disabled && element.name) {
var key = element.name, value = $(element).getValue();
if (value != undefined) {
if (result[key]) {
if (result[key].constructor != Array) result[key] = [result[key]];
result[key].push(value);
}
else result[key] = value;
}
}
return result;
});
return getHash ? data : Hash.toQueryString(data);
}
};
Form.Methods = {
serialize: function(form, getHash) {
return Form.serializeElements(Form.getElements(form), getHash);
},
getElements: function(form) {
return $A($(form).getElementsByTagName('*')).inject([],
function(elements, child) {
if (Form.Element.Serializers[child.tagName.toLowerCase()])
elements.push(Element.extend(child));
return elements;
}
);
},
getInputs: function(form, typeName, name) {
form = $(form);
var inputs = form.getElementsByTagName('input');
if (!typeName && !name) return $A(inputs).map(Element.extend);
for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
var input = inputs[i];
if ((typeName && input.type != typeName) || (name && input.name != name))
continue;
matchingInputs.push(Element.extend(input));
}
return matchingInputs;
},
disable: function(form) {
form = $(form);
form.getElements().each(function(element) {
element.blur();
element.disabled = 'true';
});
return form;
},
enable: function(form) {
form = $(form);
form.getElements().each(function(element) {
element.disabled = '';
});
return form;
},
findFirstElement: function(form) {
return $(form).getElements().find(function(element) {
return element.type != 'hidden' && !element.disabled &&
['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
});
},
focusFirstElement: function(form) {
form = $(form);
form.findFirstElement().activate();
return form;
}
}
Object.extend(Form, Form.Methods);
/*--------------------------------------------------------------------------*/
Form.Element = {
focus: function(element) {
$(element).focus();
return element;
},
select: function(element) {
$(element).select();
return element;
}
}
Form.Element.Methods = {
serialize: function(element) {
element = $(element);
if (!element.disabled && element.name) {
var value = element.getValue();
if (value != undefined) {
var pair = {};
pair[element.name] = value;
return Hash.toQueryString(pair);
}
}
return '';
},
getValue: function(element) {
element = $(element);
var method = element.tagName.toLowerCase();
return Form.Element.Serializers[method](element);
},
clear: function(element) {
$(element).value = '';
return element;
},
present: function(element) {
return $(element).value != '';
},
activate: function(element) {
element = $(element);
element.focus();
if (element.select && ( element.tagName.toLowerCase() != 'input' ||
!['button', 'reset', 'submit'].include(element.type) ) )
element.select();
return element;
},
disable: function(element) {
element = $(element);
element.disabled = true;
return element;
},
enable: function(element) {
element = $(element);
element.blur();
element.disabled = false;
return element;
}
}
Object.extend(Form.Element, Form.Element.Methods);
var Field = Form.Element;
var $F = Form.Element.getValue;
/*--------------------------------------------------------------------------*/
Form.Element.Serializers = {
input: function(element) {
switch (element.type.toLowerCase()) {
case 'checkbox':
case 'radio':
return Form.Element.Serializers.inputSelector(element);
default:
return Form.Element.Serializers.textarea(element);
}
},
inputSelector: function(element) {
return element.checked ? element.value : null;
},
textarea: function(element) {
return element.value;
},
select: function(element) {
return this[element.type == 'select-one' ?
'selectOne' : 'selectMany'](element);
},
selectOne: function(element) {
var index = element.selectedIndex;
return index >= 0 ? this.optionValue(element.options[index]) : null;
},
selectMany: function(element) {
var values, length = element.length;
if (!length) return null;
for (var i = 0, values = []; i < length; i++) {
var opt = element.options[i];
if (opt.selected) values.push(this.optionValue(opt));
}
return values;
},
optionValue: function(opt) {
return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
}
}
/*--------------------------------------------------------------------------*/
Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
initialize: function(element, frequency, callback) {
this.frequency = frequency;
this.element   = $(element);
this.callback  = callback;
this.lastValue = this.getValue();
this.registerCallback();
},
registerCallback: function() {
setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
},
onTimerEvent: function() {
var value = this.getValue();
var changed = ('string' == typeof this.lastValue && 'string' == typeof value
? this.lastValue != value : String(this.lastValue) != String(value));
if (changed) {
this.callback(this.element, value);
this.lastValue = value;
}
}
}
Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
getValue: function() {
return Form.Element.getValue(this.element);
}
});
Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
getValue: function() {
return Form.serialize(this.element);
}
});
/*--------------------------------------------------------------------------*/
Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
initialize: function(element, callback) {
this.element  = $(element);
this.callback = callback;
this.lastValue = this.getValue();
if (this.element.tagName.toLowerCase() == 'form')
this.registerFormCallbacks();
else
this.registerCallback(this.element);
},
onElementEvent: function() {
var value = this.getValue();
if (this.lastValue != value) {
this.callback(this.element, value);
this.lastValue = value;
}
},
registerFormCallbacks: function() {
Form.getElements(this.element).each(this.registerCallback.bind(this));
},
registerCallback: function(element) {
if (element.type) {
switch (element.type.toLowerCase()) {
case 'checkbox':
case 'radio':
Event.observe(element, 'click', this.onElementEvent.bind(this));
break;
default:
Event.observe(element, 'change', this.onElementEvent.bind(this));
break;
}
}
}
}
Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
getValue: function() {
return Form.Element.getValue(this.element);
}
});
Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
getValue: function() {
return Form.serialize(this.element);
}
});
if (!window.Event) {
var Event = new Object();
}
Object.extend(Event, {
KEY_BACKSPACE: 8,
KEY_TAB:       9,
KEY_RETURN:   13,
KEY_ESC:      27,
KEY_LEFT:     37,
KEY_UP:       38,
KEY_RIGHT:    39,
KEY_DOWN:     40,
KEY_DELETE:   46,
KEY_HOME:     36,
KEY_END:      35,
KEY_PAGEUP:   33,
KEY_PAGEDOWN: 34,
element: function(event) {
return event.target || event.srcElement;
},
isLeftClick: function(event) {
return (((event.which) && (event.which == 1)) ||
((event.button) && (event.button == 1)));
},
pointerX: function(event) {
return event.pageX || (event.clientX +
(document.documentElement.scrollLeft || document.body.scrollLeft));
},
pointerY: function(event) {
return event.pageY || (event.clientY +
(document.documentElement.scrollTop || document.body.scrollTop));
},
stop: function(event) {
if (event.preventDefault) {
event.preventDefault();
event.stopPropagation();
} else {
event.returnValue = false;
event.cancelBubble = true;
}
},
findElement: function(event, tagName) {
var element = Event.element(event);
while (element.parentNode && (!element.tagName ||
(element.tagName.toUpperCase() != tagName.toUpperCase())))
element = element.parentNode;
return element;
},
observers: false,
_observeAndCache: function(element, name, observer, useCapture) {
if (!this.observers) this.observers = [];
if (element.addEventListener) {
this.observers.push([element, name, observer, useCapture]);
element.addEventListener(name, observer, useCapture);
} else if (element.attachEvent) {
this.observers.push([element, name, observer, useCapture]);
element.attachEvent('on' + name, observer);
}
},
unloadCache: function() {
if (!Event.observers) return;
for (var i = 0, length = Event.observers.length; i < length; i++) {
Event.stopObserving.apply(this, Event.observers[i]);
Event.observers[i][0] = null;
}
Event.observers = false;
},
observe: function(element, name, observer, useCapture) {
element = $(element);
useCapture = useCapture || false;
if (name == 'keypress' &&
(navigator.appVersion.match(/Konqueror|Safari|KHTML/)
|| element.attachEvent))
name = 'keydown';
Event._observeAndCache(element, name, observer, useCapture);
},
stopObserving: function(element, name, observer, useCapture) {
element = $(element);
useCapture = useCapture || false;
if (name == 'keypress' &&
(navigator.appVersion.match(/Konqueror|Safari|KHTML/)
|| element.detachEvent))
name = 'keydown';
if (element.removeEventListener) {
element.removeEventListener(name, observer, useCapture);
} else if (element.detachEvent) {
try {
element.detachEvent('on' + name, observer);
} catch (e) {}
}
}
});
/* prevent memory leaks in IE */
if (navigator.appVersion.match(/\bMSIE\b/))
Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {
includeScrollOffsets: false,
prepare: function() {
this.deltaX =  window.pageXOffset
|| document.documentElement.scrollLeft
|| document.body.scrollLeft
|| 0;
this.deltaY =  window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop
|| 0;
},
realOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.scrollTop  || 0;
valueL += element.scrollLeft || 0;
element = element.parentNode;
} while (element);
return [valueL, valueT];
},
cumulativeOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop  || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
} while (element);
return [valueL, valueT];
},
positionedOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop  || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
if (element) {
if(element.tagName=='BODY') break;
var p = Element.getStyle(element, 'position');
if (p == 'relative' || p == 'absolute') break;
}
} while (element);
return [valueL, valueT];
},
offsetParent: function(element) {
if (element.offsetParent) return element.offsetParent;
if (element == document.body) return element;
while ((element = element.parentNode) && element != document.body)
if (Element.getStyle(element, 'position') != 'static')
return element;
return document.body;
},
within: function(element, x, y) {
if (this.includeScrollOffsets)
return this.withinIncludingScrolloffsets(element, x, y);
this.xcomp = x;
this.ycomp = y;
this.offset = this.cumulativeOffset(element);
return (y >= this.offset[1] &&
y <  this.offset[1] + element.offsetHeight &&
x >= this.offset[0] &&
x <  this.offset[0] + element.offsetWidth);
},
withinIncludingScrolloffsets: function(element, x, y) {
var offsetcache = this.realOffset(element);
this.xcomp = x + offsetcache[0] - this.deltaX;
this.ycomp = y + offsetcache[1] - this.deltaY;
this.offset = this.cumulativeOffset(element);
return (this.ycomp >= this.offset[1] &&
this.ycomp <  this.offset[1] + element.offsetHeight &&
this.xcomp >= this.offset[0] &&
this.xcomp <  this.offset[0] + element.offsetWidth);
},
overlap: function(mode, element) {
if (!mode) return 0;
if (mode == 'vertical')
return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
element.offsetHeight;
if (mode == 'horizontal')
return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
element.offsetWidth;
},
page: function(forElement) {
var valueT = 0, valueL = 0;
var element = forElement;
do {
valueT += element.offsetTop  || 0;
valueL += element.offsetLeft || 0;
if (element.offsetParent==document.body)
if (Element.getStyle(element,'position')=='absolute') break;
} while (element = element.offsetParent);
element = forElement;
do {
if (!window.opera || element.tagName=='BODY') {
valueT -= element.scrollTop  || 0;
valueL -= element.scrollLeft || 0;
}
} while (element = element.parentNode);
return [valueL, valueT];
},
clone: function(source, target) {
var options = Object.extend({
setLeft:    true,
setTop:     true,
setWidth:   true,
setHeight:  true,
offsetTop:  0,
offsetLeft: 0
}, arguments[2] || {})
source = $(source);
var p = Position.page(source);
target = $(target);
var delta = [0, 0];
var parent = null;
if (Element.getStyle(target,'position') == 'absolute') {
parent = Position.offsetParent(target);
delta = Position.page(parent);
}
if (parent == document.body) {
delta[0] -= document.body.offsetLeft;
delta[1] -= document.body.offsetTop;
}
if(options.setLeft)   target.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
if(options.setTop)    target.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
if(options.setHeight) target.style.height = source.offsetHeight + 'px';
},
absolutize: function(element) {
element = $(element);
if (element.style.position == 'absolute') return;
Position.prepare();
var offsets = Position.positionedOffset(element);
var top     = offsets[1];
var left    = offsets[0];
var width   = element.clientWidth;
var height  = element.clientHeight;
element._originalLeft   = left - parseFloat(element.style.left  || 0);
element._originalTop    = top  - parseFloat(element.style.top || 0);
element._originalWidth  = element.style.width;
element._originalHeight = element.style.height;
element.style.position = 'absolute';
element.style.top    = top + 'px';
element.style.left   = left + 'px';
element.style.width  = width + 'px';
element.style.height = height + 'px';
},
relativize: function(element) {
element = $(element);
if (element.style.position == 'relative') return;
Position.prepare();
element.style.position = 'relative';
var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
element.style.top    = top + 'px';
element.style.left   = left + 'px';
element.style.height = element._originalHeight;
element.style.width  = element._originalWidth;
}
}
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
Position.cumulativeOffset = function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop  || 0;
valueL += element.offsetLeft || 0;
if (element.offsetParent == document.body)
if (Element.getStyle(element, 'position') == 'absolute') break;
element = element.offsetParent;
} while (element);
return [valueL, valueT];
}
}
Element.addMethods();
/**
* CPAINT - Cross-Platform Asynchronous INterface Toolkit
*
* http://sf.net/projects/cpaint
*
* released under the terms of the LGPL
* see http://www.fsf.org/licensing/licenses/lgpl.txt for details
*
* @package      CPAINT
* @access       public
* @copyright    Copyright (c) 2005-2006 Paul Sullivan, Dominique Stender - http://sf.net/projects/cpaint
* @author       Paul Sullivan <wiley14@gmail.com>
* @author       Dominique Stender <dstender@st-webdevelopment.de>
* @author		Stephan Tijink <stijink@googlemail.com>
* @version      $Id$
*/
function cpaint() {
/**
* CPAINT version
*
* @access     protected
* @var        string      version
*/
this.version = '2.0.2';
/**
* configuration options both for this class but also for  the cpaint_call() objects.
*
* @access     protected
* @var        array       config
*/
var config                      = new Array();
config['debugging']             = -1;
config['proxy_url']             = '';
config['transfer_mode']         = 'GET';
config['async']                 = true;
config['response_type']         = 'OBJECT';
config['persistent_connection'] = false;
config['use_cpaint_api']        = true;
/**
* maintains the next free index in the stack
*
* @access   protected
* @var      integer   stack_count
*/
var stack_count = 0;
/**
* property returns whether or not the browser is AJAX capable
*
* @access		public
* @return		boolean
*/
this.capable = test_ajax_capability();
/**
* switches debug mode on/off.
*
* @access   public
* @param    boolean    debug    debug flag
* @return   void
*/
this.set_debug = function() {
if (typeof arguments[0] == 'boolean') {
if (arguments[0] === true) {
config['debugging'] = 1;
} else {
config['debugging'] = 0;
}
} else if (typeof arguments[0] == 'number') {
config['debugging'] = Math.round(arguments[0]);
}
}
/**
* defines the URL of the proxy script.
*
* @access   public
* @param    string    proxy_url    URL of the proxyscript to connect
* @return   void
*/
this.set_proxy_url = function() {
if (typeof arguments[0] == 'string') {
config['proxy_url'] = arguments[0];
}
}
/**
* sets the transfer_mode (GET|POST).
*
* @access   public
* @param    string    transfer_mode    transfer_mode
* @return   void
*/
this.set_transfer_mode = function() {
if (arguments[0].toUpperCase() == 'GET'
|| arguments[0].toUpperCase() == 'POST') {
config['transfer_mode'] = arguments[0].toUpperCase();
}
}
/**
* sets the flag whether or not to use asynchronous calls.
*
* @access   public
* @param    boolean    async    syncronization flag
* @return   void
*/
this.set_async = function() {
if (typeof arguments[0] == 'boolean') {
config['async'] = arguments[0];
}
}
/**
* defines the response type.
*
* allowed values are:
*   TEXT    = raw text response
*   XML     = raw XMLHttpObject
*   OBJECT  = parsed JavaScript object structure from XMLHttpObject
*
* the default is OBJECT.
*
* @access   public
* @param    string    response_type    response type
* @return   void
*/
this.set_response_type = function() {
if (arguments[0].toUpperCase() == 'TEXT'
|| arguments[0].toUpperCase() == 'XML'
|| arguments[0].toUpperCase() == 'OBJECT'
|| arguments[0].toUpperCase() == 'E4X'
|| arguments[0].toUpperCase() == 'JSON') {
config['response_type'] = arguments[0].toUpperCase();
}
}
/**
* sets the flag whether or not to use a persistent connection.
*
* @access   public
* @param    boolean    persistent_connection    persistance flag
* @return   void
*/
this.set_persistent_connection = function() {
if (typeof arguments[0] == 'boolean') {
config['persistent_connection'] = arguments[0];
}
}
/**
* sets the flag whether or not to use the cpaint api on the backend.
*
* @access    public
* @param     boolean    cpaint_api      api_flag
* @return    void
*/
this.set_use_cpaint_api = function() {
if (typeof arguments[0] == 'boolean') {
config['use_cpaint_api'] = arguments[0];
}
}
/**
* tests whether one of the necessary implementations
* of the XMLHttpRequest class are available
*
* @access     protected
* @return     boolean
*/
function test_ajax_capability() {
var cpc = new cpaint_call(0, config, this.version);
return cpc.test_ajax_capability();
}
/**
* takes the arguments supplied and triggers a call to the CPAINT backend
* based on the settings.
*
* upon response cpaint_call.callback() will automatically be called
* to perform post-processing operations.
*
* @access   public
* @param    string    url                 remote URL to call
* @param    string    remote_method       remote method to call
* @param    object    client_callback     client side callback method to deliver the remote response to. do NOT supply a string!
* @param    mixed     argN                remote parameters from now on
* @return   void
*/
this.call = function() {
var use_stack = -1;
if (config['persistent_connection'] == true
&& __cpaint_stack[0] != null) {
switch (__cpaint_stack[0].get_http_state()) {
case -1:
use_stack = 0;
debug('no XMLHttpObject object to re-use for persistence, creating new one later', 2);
break;
case 4:
use_stack = 0
debug('re-using the persistent connection', 2);
break;
default:
debug('the persistent connection is in use - skipping this request', 2);
}
} else if (config['persistent_connection'] == true) {
use_stack = 0;
__cpaint_stack[use_stack] = new cpaint_call(use_stack, config, this.version);
debug('no cpaint_call object available for re-use, created new one', 2);
} else {
use_stack = stack_count;
__cpaint_stack[use_stack] = new cpaint_call(use_stack, config, this.version);
debug('no cpaint_call object created new one', 2);
}
if (use_stack != -1) {
__cpaint_stack[use_stack].set_client_callback(arguments[2]);
if (config['proxy_url'] != '') {
__cpaint_stack[use_stack].call_proxy(arguments);
} else {
__cpaint_stack[use_stack].call_direct(arguments);
}
stack_count++;
debug('stack size: ' + __cpaint_stack.length, 2);
}
}
/**
* debug method
*
* @access  protected
* @param   string       message         the message to debug
* @param   integer      debug_level     debug level at which the message appears
* @return  void
*/
var debug  = function(message, debug_level) {
var prefix = '[CPAINT Debug] ';
if (debug_level < 1) {
prefix = '[CPAINT Error] ';
}
if (config['debugging'] >= debug_level) {
alert(prefix + message);
}
}
}
/**
* internal FIFO stack of cpaint_call() objects.
*
* @access   protected
* @var      array    __cpaint_stack
*/
var __cpaint_stack = new Array();
/**
* local instance of cpaint_transformer
* MSIE is unable to handle static classes... sheesh.
*
* @access   public
* @var      object    __cpaint_transformer
*/
var __cpaint_transformer = new cpaint_transformer();
/**
* transport agent class
*
* creates the request object, takes care of the response, handles the
* client callback. Is configured by the cpaint() object.
*
* @package      CPAINT
* @access       public
* @copyright    Copyright (c) 2005-2006 Paul Sullivan, Dominique Stender - http://sf.net/projects/cpaint
* @author       Dominique Stender <dstender@st-webdevelopment.de>
* @author       Paul Sullivan <wiley14@gmail.com>
* @param        integer     stack_id      stack Id in cpaint
* @param        array       config        configuration array for this call
* @param        string      version       CPAINT API version
*/
function cpaint_call() {
/**
* CPAINT version
*
* @access     protected
* @var        string      version
*/
var version = arguments[2];
/**
* configuration options both for this class objects.
*
* @access     protected
* @var        array       config
*/
var config                      = new Array();
config['debugging']             = arguments[1]['debugging'];
config['proxy_url']             = arguments[1]['proxy_url'];
config['transfer_mode']         = arguments[1]['transfer_mode'];
config['async']                 = arguments[1]['async'];
config['response_type']         = arguments[1]['response_type'];
config['persistent_connection'] = arguments[1]['persistent_connection'];
config['use_cpaint_api']        = arguments[1]['use_cpaint_api'];
/**
* XMLHttpObject used for this request.
*
* @access   protected
* @var      object     httpobj
*/
var httpobj    = false;
/**
* client callback function.
*
* @access   public
* @var      function    client_callback
*/
var client_callback;
/**
* stores the stack Id within the cpaint object
*
* @access   protected
* @var      stack_id
*/
var stack_id = arguments[0];
/**
* sets the client callback function.
*
* @access   public
* @param    function    client_callback     the client callback function
* @return   void
*/
this.set_client_callback = function() {
if (typeof arguments[0] == 'function') {
client_callback = arguments[0];
}
}
/**
* returns the ready state of the internal XMLHttpObject
*
* if no such object was set up already, -1 is returned
*
* @access     public
* @return     integer
*/
this.get_http_state = function() {
var return_value = -1;
if (typeof httpobj == 'object') {
return_value = httpobj.readyState;
}
return return_value;
}
/**
* internal method for remote calls to the local server without use of the proxy script.
*
* @access   public
* @param    array    call_arguments    array of arguments initially passed to cpaint.call()
* @return   void
*/
this.call_direct = function(call_arguments) {
var url             = call_arguments[0];
var remote_method   = call_arguments[1];
var querystring     = '';
var i               = 0;
if (url == 'SELF') {
url = document.location.href;
}
if (config['use_cpaint_api'] == true) {
for (i = 3; i < call_arguments.length; i++) {
if ((typeof call_arguments[i] == 'string'
&& call_arguments[i] != ''
&& call_arguments[i].search(/^\s+$/g) == -1)
&& !isNaN(call_arguments[i])
&& isFinite(call_arguments[i])) {
querystring += '&cpaint_argument[]=' + encodeURIComponent(JSON.stringify(Number(call_arguments[i])));
} else {
querystring += '&cpaint_argument[]=' + encodeURIComponent(JSON.stringify(call_arguments[i]));
}
}
querystring += '&cpaint_response_type=' + config['response_type'];
if (config['transfer_mode'] == 'GET') {
if(url.indexOf('?') != -1) {
url = url + '&cpaint_function=' + remote_method +	querystring;
} else {
url = url + '?cpaint_function=' + remote_method +	querystring;
}
} else {
querystring = 'cpaint_function=' + remote_method + querystring;
}
} else {
for (i = 3; i < call_arguments.length; i++) {
if (i == 3) {
querystring += encodeURIComponent(call_arguments[i]);
} else {
querystring += '&' + encodeURIComponent(call_arguments[i]);
}
}
if (config['transfer_mode'] == 'GET') {
url = url + querystring;
}
}
get_connection_object();
debug('opening connection to "' + url + '"', 1);
httpobj.open(config['transfer_mode'], url, config['async']);
if (config['transfer_mode'] == 'POST') {
try {
httpobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
} catch (cp_err) {
debug('POST cannot be completed due to incompatible browser.  Use GET as your request method.', 0);
}
}
httpobj.setRequestHeader('X-Powered-By', 'CPAINT v' + version + ' :: http://sf.net/projects/cpaint');
httpobj.onreadystatechange = callback;
if (config['transfer_mode'] == 'GET') {
httpobj.send(null);
} else {
debug('sending query: ' + querystring, 1);
httpobj.send(querystring);
}
if (config['async'] == true) {
callback();
}
}
/**
* internal method for calls to remote servers through the proxy script.
*
* @access   public
* @param    array    call_arguments    array of arguments passed to cpaint.call()
* @return   void
*/
this.call_proxy = function(call_arguments) {
var proxyscript     = config['proxy_url'];
var url             = call_arguments[0];
var remote_method   = call_arguments[1];
var querystring     = '';
var i               = 0;
var querystring_argument_prefix = 'cpaint_argument[]=';
if (config['use_cpaint_api'] == false) {
querystring_argument_prefix = '';
}
for (i = 3; i < call_arguments.length; i++) {
if (config['use_cpaint_api'] == true) {
if ((typeof call_arguments[i] == 'string'
&& call_arguments[i] != ''
&& call_arguments[i].search(/^\s+$/g) == -1)
&& !isNaN(call_arguments[i])
&& isFinite(call_arguments[i])) {
querystring += encodeURIComponent(querystring_argument_prefix + JSON.stringify(Number(call_arguments[i])) + '&');
} else {
querystring += encodeURIComponent(querystring_argument_prefix + JSON.stringify(call_arguments[i]) + '&');
}
} else {
querystring += encodeURIComponent(querystring_argument_prefix + call_arguments[i] + '&');
}
}
if (config['use_cpaint_api'] == true) {
querystring += encodeURIComponent('&cpaint_function=' + remote_method);
querystring += encodeURIComponent('&cpaint_responsetype=' + config['response_type']);
}
if (config['transfer_mode'] == 'GET') {
proxyscript += '?cpaint_remote_url=' + encodeURIComponent(url)
+ '&cpaint_remote_query=' + querystring
+ '&cpaint_remote_method=' + config['transfer_mode']
+ '&cpaint_response_type=' + config['response_type'];
} else {
querystring = 'cpaint_remote_url=' + encodeURIComponent(url)
+ '&cpaint_remote_query=' + querystring
+ '&cpaint_remote_method=' + config['transfer_mode']
+ '&cpaint_response_type=' + config['response_type'];
}
get_connection_object();
debug('opening connection to proxy "' + proxyscript + '"', 1);
httpobj.open(config['transfer_mode'], proxyscript, config['async']);
if (config['transfer_mode'] == 'POST') {
try {
httpobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
} catch (cp_err) {
debug('POST cannot be completed due to incompatible browser.  Use GET as your request method.', 0);
}
}
httpobj.setRequestHeader('X-Powered-By', 'CPAINT v' + version);
httpobj.onreadystatechange = callback;
if (config['transfer_mode'] == 'GET') {
httpobj.send(null);
} else {
debug('sending query: ' + querystring, 1);
httpobj.send(querystring);
}
if (config['async'] == false) {
callback();
}
}
this.test_ajax_capability = function() {
return get_connection_object();
}
/**
* creates a new connection object.
*
* @access   protected
* @return   boolean
*/
var get_connection_object = function() {
var return_value    = false;
var new_connection  = false;
if (config['persistent_connection'] == false) {
debug('Using new connection object', 1);
new_connection = true;
} else {
debug('Using shared connection object.', 1);
if (typeof httpobj != 'object') {
debug('Getting new persistent connection object.', 1);
new_connection = true;
}
}
if (new_connection == true) {
try {
httpobj = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
httpobj = new ActiveXObject('Microsoft.XMLHTTP');
} catch (oc) {
httpobj = null;
}
}
if (!httpobj && typeof XMLHttpRequest != 'undefined') {
httpobj = new XMLHttpRequest();
}
if (!httpobj) {
debug('Could not create connection object', 0);
} else {
return_value = true;
}
}
if (httpobj.readyState != 4) {
httpobj.abort();
}
return return_value;
}
/**
* internal callback function.
*
* will perform some consistency checks (response code, NULL value testing)
* and if response_type = 'OBJECT' it will automatically call
* cpaint_call.parse_ajax_xml() to have a JavaScript object structure generated.
*
* after all that is done the client side callback function will be called
* with the generated response as single value.
*
* @access   protected
* @return   void
*/
var callback = function() {
var response = null;
if (httpobj.readyState == 4
&& httpobj.status == 200) {
debug(httpobj.responseText, 1);
debug('using response type ' + config['response_type'], 2);
switch (config['response_type']) {
case 'XML':
debug(httpobj.responseXML, 2);
response = __cpaint_transformer.xml_conversion(httpobj.responseXML);
break;
case 'OBJECT':
response = __cpaint_transformer.object_conversion(httpobj.responseXML);
break;
case 'TEXT':
response = __cpaint_transformer.text_conversion(httpobj.responseText);
break;
case 'E4X':
response = __cpaint_transformer.e4x_conversion(httpobj.responseText);
break;
case 'JSON':
response = __cpaint_transformer.json_conversion(httpobj.responseText);
break;
default:
debug('invalid response type \'' + response_type + '\'', 0);
}
if (response != null
&& typeof client_callback == 'function') {
client_callback(response, httpobj.responseText);
}
remove_from_stack();
} else if (httpobj.readyState == 4
&& httpobj.status != 200) {
debug('invalid HTTP response code \'' + Number(httpobj.status) + '\'', 0);
}
}
/**
* removes an entry from the stack
*
* @access     protected
* @return     void
*/
var remove_from_stack = function() {
if (typeof stack_id == 'number'
&& __cpaint_stack[stack_id]
&& config['persistent_connection'] == false) {
__cpaint_stack[stack_id] = null;
}
}
/**
* debug method
*
* @access  protected
* @param   string       message         the message to debug
* @param   integer      debug_level     debug level at which the message appears
* @return  void
*/
var debug  = function(message, debug_level) {
var prefix = '[CPAINT Debug] ';
if (config['debugging'] < 1) {
prefix = '[CPAINT Error] ';
}
if (config['debugging'] >= debug_level) {
alert(prefix + message);
}
}
}
/**
* CPAINT transformation object
*
* @package      CPAINT
* @access       public
* @copyright    Copyright (c) 2005-2006 Paul Sullivan, Dominique Stender - http://sf.net/projects/cpaint
* @author       Paul Sullivan <wiley14@gmail.com>
* @author       Dominique Stender <dstender@st-webdevelopment.de>
*/
function cpaint_transformer() {
/**
* will take a XMLHttpObject and generate a JavaScript
* object structure from it.
*
* is internally called by cpaint_call.callback() if necessary.
* will call cpaint_call.create_object_structure() to create nested object structures.
*
* @access   public
* @param    object    xml_document  a XMLHttpObject
* @return   object
*/
this.object_conversion = function(xml_document) {
var return_value  = new cpaint_result_object();
var i             = 0;
var firstNodeName = '';
if (typeof xml_document == 'object'
&& xml_document != null) {
for (i = 0; i < xml_document.childNodes.length; i++) {
if (xml_document.childNodes[i].nodeType == 1) {
firstNodeName = xml_document.childNodes[i].nodeName;
break;
}
}
var ajax_response = xml_document.getElementsByTagName(firstNodeName);
return_value[firstNodeName] = new Array();
for (i = 0; i < ajax_response.length; i++) {
var tmp_node = create_object_structure(ajax_response[i]);
tmp_node.id  = ajax_response[i].getAttribute('id')
return_value[firstNodeName].push(tmp_node);
}
} else {
debug('received invalid XML response', 0);
}
return return_value;
}
/**
* performs the necessary conversions for the XML response type
*
* @access   public
* @param    object    xml_document  a XMLHttpObject
* @return   object
*/
this.xml_conversion = function(xml_document) {
return xml_document;
}
/**
* performs the necessary conversions for the TEXT response type
*
* @access   public
* @param    string    text  the response text
* @return   string
*/
this.text_conversion = function(text) {
return decode(text);
}
/**
* performs the necessary conversions for the E4X response type
*
* @access   public
* @param    string    text  the response text
* @return   string
*/
this.e4x_conversion = function(text) {
text = text.replace(/^\<\?xml[^>]+\>/, '');
return new XML(text);
}
/**
* performs the necessary conversions for the JSON response type
*
* @access   public
* @param    string    text  the response text
* @return   string
*/
this.json_conversion = function(text) {
try {
var retObj = eval('(' + text + ')');
} catch (e) {
alert(e);
alert(text);
}
return retObj;
}
/**
* this method takes a HTML / XML node object and creates a
* JavaScript object structure from it.
*
* @access   public
* @param    object    stream    a node in the XML structure
* @return   object
*/
var create_object_structure = function(stream) {
var return_value = new cpaint_result_object();
var node_name = '';
var i         = 0;
var attrib    = 0;
if (stream.hasChildNodes() == true) {
for (i = 0; i < stream.childNodes.length; i++) {
node_name = stream.childNodes[i].nodeName;
node_name = node_name.replace(/[^a-zA-Z0-9_]*/g, '');
if (typeof return_value[node_name] != 'object') {
return_value[node_name] = new Array();
}
if (stream.childNodes[i].nodeType == 1) {
var tmp_node  = create_object_structure(stream.childNodes[i]);
for (attrib = 0; attrib < stream.childNodes[i].attributes.length; attrib++) {
tmp_node.set_attribute(stream.childNodes[i].attributes[attrib].nodeName, stream.childNodes[i].attributes[attrib].nodeValue);
}
return_value[node_name].push(tmp_node);
} else if (stream.childNodes[i].nodeType == 3) {
return_value.data  = decode(String(stream.firstChild.data));
}
}
}
return return_value;
}
/**
* converts an encoded text back to viewable characters.
*
* @access     public
* @param      string      rawtext     raw text as provided by the backend
* @return     mixed
*/
var decode = function(rawtext) {
var plaintext = '';
var i         = 0;
var c1        = 0;
var c2        = 0;
var c3        = 0;
var u         = 0;
var t         = 0;
while (i < rawtext.length) {
if (rawtext.charAt(i) == '\\'
&& rawtext.charAt(i + 1) == 'u') {
u = 0;
for (j = 2; j < 6; j += 1) {
t = parseInt(rawtext.charAt(i + j), 16);
if (!isFinite(t)) {
break;
}
u = u * 16 + t;
}
plaintext += String.fromCharCode(u);
i       += 6;
} else {
plaintext += rawtext.charAt(i);
i++;
}
}
if (plaintext != ''
&& plaintext.search(/^\s+$/g) == -1
&& !isNaN(plaintext)
&& isFinite(plaintext)) {
plaintext = Number(plaintext);
}
return plaintext;
}
}
/**
* this is the basic prototype for a cpaint node object
* as used in cpaint_call.parse_ajax_xml()
*
* @package      CPAINT
* @access       public
* @copyright    Copyright (c) 2005-2006 Paul Sullivan, Dominique Stender - http://sf.net/projects/cpaint
* @author       Paul Sullivan <wiley14@gmail.com>
* @author       Dominique Stender <dstender@st-webdevelopment.de>
*/
function cpaint_result_object() {
this.id           = 0;
this.data         = '';
var __attributes  = new Array();
/**
* Returns a subnode with the given type and id.
*
* @access     public
* @param      string    type    The type of the subnode. Equivalent to the XML tag name.
* @param      string    id      The id of the subnode. Equivalent to the XML tag names id attribute.
* @return     object
*/
this.find_item_by_id = function() {
var return_value  = null;
var type    = arguments[0];
var id      = arguments[1];
var i       = 0;
if (this[type]) {
for (i = 0; i < this[type].length; i++) {
if (this[type][i].get_attribute('id') == id) {
return_value = this[type][i];
break;
}
}
}
return return_value;
}
/**
* retrieves the value of an attribute.
*
* @access   public
* @param    string    name    name of the attribute
* @return   mixed
*/
this.get_attribute = function() {
var return_value  = null;
var id            = arguments[0];
if (typeof __attributes[id] != 'undefined') {
return_value = __attributes[id];
}
return return_value;
}
/**
* assigns a value to an attribute.
*
* if that attribute does not exist it will be created.
*
* @access     public
* @param      string    name    name of the attribute
* @param      string    value   value of the attribute
* @return     void
*/
this.set_attribute = function() {
__attributes[arguments[0]] = arguments[1];
}
}
/*
Copyright (c) 2005 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
Array.prototype.______array = '______array';
var JSON = {
org: 'http://www.JSON.org',
copyright: '(c)2005 JSON.org',
license: 'http://www.crockford.com/JSON/license.html',
stringify: function (arg) {
var c, i, l, s = '', v;
var numeric = true;
switch (typeof arg) {
case 'object':
if (arg) {
if (arg.______array == '______array') {
for (i in arg) {
if (i != '______array'
&& (isNaN(i)
|| !isFinite(i))) {
numeric = false;
break;
}
}
if (numeric == true) {
for (i = 0; i < arg.length; ++i) {
if (typeof arg[i] != 'undefined') {
v = this.stringify(arg[i]);
if (s) {
s += ',';
}
s += v;
} else {
s += ',null';
}
}
return '[' + s + ']';
} else {
for (i in arg) {
if (i != '______array') {
v = arg[i];
if (typeof v != 'undefined' && typeof v != 'function') {
v = this.stringify(v);
if (s) {
s += ',';
}
s += this.stringify(i) + ':' + v;
}
}
}
return '{' + s + '}';
}
} else if (typeof arg.toString != 'undefined') {
for (i in arg) {
v = arg[i];
if (typeof v != 'undefined' && typeof v != 'function') {
v = this.stringify(v);
if (s) {
s += ',';
}
s += this.stringify(i) + ':' + v;
}
}
return '{' + s + '}';
}
}
return 'null';
case 'number':
return isFinite(arg) ? String(arg) : 'null';
case 'string':
l = arg.length;
s = '"';
for (i = 0; i < l; i += 1) {
c = arg.charAt(i);
if (c >= ' ') {
if (c == '\\' || c == '"') {
s += '\\';
}
s += c;
} else {
switch (c) {
case '\b':
s += '\\b';
break;
case '\f':
s += '\\f';
break;
case '\n':
s += '\\n';
break;
case '\r':
s += '\\r';
break;
case '\t':
s += '\\t';
break;
default:
c = c.charCodeAt();
s += '\\u00' + Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}
}
}
return s + '"';
case 'boolean':
return String(arg);
default:
return 'null';
}
},
parse: function (text) {
var at = 0;
var ch = ' ';
function error(m) {
throw {
name: 'JSONError',
message: m,
at: at - 1,
text: text
};
}
function next() {
ch = text.charAt(at);
at += 1;
return ch;
}
function white() {
while (ch != '' && ch <= ' ') {
next();
}
}
function str() {
var i, s = '', t, u;
if (ch == '"') {
outer:      while (next()) {
if (ch == '"') {
next();
return s;
} else if (ch == '\\') {
switch (next()) {
case 'b':
s += '\b';
break;
case 'f':
s += '\f';
break;
case 'n':
s += '\n';
break;
case 'r':
s += '\r';
break;
case 't':
s += '\t';
break;
case 'u':
u = 0;
for (i = 0; i < 4; i += 1) {
t = parseInt(next(), 16);
if (!isFinite(t)) {
break outer;
}
u = u * 16 + t;
}
s += String.fromCharCode(u);
break;
default:
s += ch;
}
} else {
s += ch;
}
}
}
error("Bad string");
}
function arr() {
var a = [];
if (ch == '[') {
next();
white();
if (ch == ']') {
next();
return a;
}
while (ch) {
a.push(val());
white();
if (ch == ']') {
next();
return a;
} else if (ch != ',') {
break;
}
next();
white();
}
}
error("Bad array");
}
function obj() {
var k, o = {};
if (ch == '{') {
next();
white();
if (ch == '}') {
next();
return o;
}
while (ch) {
k = str();
white();
if (ch != ':') {
break;
}
next();
o[k] = val();
white();
if (ch == '}') {
next();
return o;
} else if (ch != ',') {
break;
}
next();
white();
}
}
error("Bad object");
}
function assoc() {
var k, a = [];
if (ch == '<') {
next();
white();
if (ch == '>') {
next();
return a;
}
while (ch) {
k = str();
white();
if (ch != ':') {
break;
}
next();
a[k] = val();
white();
if (ch == '>') {
next();
return a;
} else if (ch != ',') {
break;
}
next();
white();
}
}
error("Bad associative array");
}
function num() {
var n = '', v;
if (ch == '-') {
n = '-';
next();
}
while (ch >= '0' && ch <= '9') {
n += ch;
next();
}
if (ch == '.') {
n += '.';
while (next() && ch >= '0' && ch <= '9') {
n += ch;
}
}
if (ch == 'e' || ch == 'E') {
n += 'e';
next();
if (ch == '-' || ch == '+') {
n += ch;
next();
}
while (ch >= '0' && ch <= '9') {
n += ch;
next();
}
}
v = +n;
if (!isFinite(v)) {
error("Bad number");
} else {
return v;
}
}
function word() {
switch (ch) {
case 't':
if (next() == 'r' && next() == 'u' && next() == 'e') {
next();
return true;
}
break;
case 'f':
if (next() == 'a' && next() == 'l' && next() == 's' &&
next() == 'e') {
next();
return false;
}
break;
case 'n':
if (next() == 'u' && next() == 'l' && next() == 'l') {
next();
return null;
}
break;
}
error("Syntax error");
}
function val() {
white();
switch (ch) {
case '{':
return obj();
case '[':
return arr();
case '<':
return assoc();
case '"':
return str();
case '-':
return num();
default:
return ch >= '0' && ch <= '9' ? num() : word();
}
}
return val();
}
}
/**************************************************
* dom-drag.js
* 09.25.2001
* www.youngpup.net
**************************************************
* 10.28.2001 - fixed minor bug where events
* sometimes fired off the handle, not the root.
**************************************************/
var Drag = {
obj : null,
init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
{
o.onmousedown	= Drag.start;
o.hmode			= bSwapHorzRef ? false : true ;
o.vmode			= bSwapVertRef ? false : true ;
o.root = oRoot && oRoot != null ? oRoot : o ;
if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";
o.minX	= typeof minX != 'undefined' ? minX : null;
o.minY	= typeof minY != 'undefined' ? minY : null;
o.maxX	= typeof maxX != 'undefined' ? maxX : null;
o.maxY	= typeof maxY != 'undefined' ? maxY : null;
o.xMapper = fXMapper ? fXMapper : null;
o.yMapper = fYMapper ? fYMapper : null;
o.root.onDragStart	= new Function();
o.root.onDragEnd	= new Function();
o.root.onDrag		= new Function();
},
start : function(e)
{
var o = Drag.obj = this;
e = Drag.fixE(e);
var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
o.root.onDragStart(x, y);
o.lastMouseX	= e.clientX;
o.lastMouseY	= e.clientY;
if (o.hmode) {
if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
} else {
if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
}
if (o.vmode) {
if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
} else {
if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
}
document.onmousemove	= Drag.drag;
document.onmouseup		= Drag.end;
return false;
},
drag : function(e)
{
e = Drag.fixE(e);
var o = Drag.obj;
var ey	= e.clientY;
var ex	= e.clientX;
var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
var nx, ny;
if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);
nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));
if (o.xMapper)		nx = o.xMapper(y)
else if (o.yMapper)	ny = o.yMapper(x)
Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
Drag.obj.lastMouseX	= ex;
Drag.obj.lastMouseY	= ey;
Drag.obj.root.onDrag(nx, ny);
return false;
},
end : function()
{
document.onmousemove = null;
document.onmouseup   = null;
Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]),
parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
Drag.obj = null;
},
fixE : function(e)
{
if (typeof e == 'undefined') e = window.event;
if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
return e;
}
};
String.prototype.parseColor = function() {
var color = '#';
if(this.slice(0,4) == 'rgb(') {
var cols = this.slice(4,this.length-1).split(',');
var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
} else {
if(this.slice(0,1) == '#') {
if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
if(this.length==7) color = this.toLowerCase();
}
}
return(color.length==7 ? color : (arguments[0] || this));
}
/*--------------------------------------------------------------------------*/
Element.collectTextNodes = function(element) {
return $A($(element).childNodes).collect( function(node) {
return (node.nodeType==3 ? node.nodeValue :
(node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
}).flatten().join('');
}
Element.collectTextNodesIgnoreClass = function(element, className) {
return $A($(element).childNodes).collect( function(node) {
return (node.nodeType==3 ? node.nodeValue :
((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
Element.collectTextNodesIgnoreClass(node, className) : ''));
}).flatten().join('');
}
Element.setContentZoom = function(element, percent) {
element = $(element);
element.setStyle({fontSize: (percent/100) + 'em'});
if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
return element;
}
Element.getOpacity = function(element){
return $(element).getStyle('opacity');
}
Element.setOpacity = function(element, value){
return $(element).setStyle({opacity:value});
}
Element.getInlineOpacity = function(element){
return $(element).style.opacity || '';
}
Element.forceRerendering = function(element) {
try {
element = $(element);
var n = document.createTextNode(' ');
element.appendChild(n);
element.removeChild(n);
} catch(e) { }
};
/*--------------------------------------------------------------------------*/
Array.prototype.call = function() {
var args = arguments;
this.each(function(f){ f.apply(this, args) });
}
/*--------------------------------------------------------------------------*/
var Effect = {
_elementDoesNotExistError: {
name: 'ElementDoesNotExistError',
message: 'The specified DOM element does not exist, but is required for this effect to operate'
},
tagifyText: function(element) {
if(typeof Builder == 'undefined')
throw("Effect.tagifyText requires including script.aculo.us' builder.js library");
var tagifyStyle = 'position:relative';
if(/MSIE/.test(navigator.userAgent) && !window.opera) tagifyStyle += ';zoom:1';
element = $(element);
$A(element.childNodes).each( function(child) {
if(child.nodeType==3) {
child.nodeValue.toArray().each( function(character) {
element.insertBefore(
Builder.node('span',{style: tagifyStyle},
character == ' ' ? String.fromCharCode(160) : character),
child);
});
Element.remove(child);
}
});
},
multiple: function(element, effect) {
var elements;
if(((typeof element == 'object') ||
(typeof element == 'function')) &&
(element.length))
elements = element;
else
elements = $(element).childNodes;
var options = Object.extend({
speed: 0.1,
delay: 0.0
}, arguments[2] || {});
var masterDelay = options.delay;
$A(elements).each( function(element, index) {
new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
});
},
PAIRS: {
'slide':  ['SlideDown','SlideUp'],
'blind':  ['BlindDown','BlindUp'],
'appear': ['Appear','Fade']
},
toggle: function(element, effect) {
element = $(element);
effect = (effect || 'appear').toLowerCase();
var options = Object.extend({
queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
}, arguments[2] || {});
Effect[element.visible() ?
Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
}
};
var Effect2 = Effect; // deprecated
/* ------------- transitions ------------- */
Effect.Transitions = {
linear: Prototype.K,
sinoidal: function(pos) {
return (-Math.cos(pos*Math.PI)/2) + 0.5;
},
reverse: function(pos) {
return 1-pos;
},
flicker: function(pos) {
return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
},
wobble: function(pos) {
return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
},
pulse: function(pos, pulses) {
pulses = pulses || 5;
return (
Math.round((pos % (1/pulses)) * pulses) == 0 ?
((pos * pulses * 2) - Math.floor(pos * pulses * 2)) :
1 - ((pos * pulses * 2) - Math.floor(pos * pulses * 2))
);
},
none: function(pos) {
return 0;
},
full: function(pos) {
return 1;
}
};
/* ------------- core effects ------------- */
Effect.ScopedQueue = Class.create();
Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), {
initialize: function() {
this.effects  = [];
this.interval = null;
},
_each: function(iterator) {
this.effects._each(iterator);
},
add: function(effect) {
var timestamp = new Date().getTime();
var position = (typeof effect.options.queue == 'string') ?
effect.options.queue : effect.options.queue.position;
switch(position) {
case 'front':
this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
e.startOn  += effect.finishOn;
e.finishOn += effect.finishOn;
});
break;
case 'with-last':
timestamp = this.effects.pluck('startOn').max() || timestamp;
break;
case 'end':
timestamp = this.effects.pluck('finishOn').max() || timestamp;
break;
}
effect.startOn  += timestamp;
effect.finishOn += timestamp;
if(!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
this.effects.push(effect);
if(!this.interval)
this.interval = setInterval(this.loop.bind(this), 15);
},
remove: function(effect) {
this.effects = this.effects.reject(function(e) { return e==effect });
if(this.effects.length == 0) {
clearInterval(this.interval);
this.interval = null;
}
},
loop: function() {
var timePos = new Date().getTime();
for(var i=0, len=this.effects.length;i<len;i++)
if(this.effects[i]) this.effects[i].loop(timePos);
}
});
Effect.Queues = {
instances: $H(),
get: function(queueName) {
if(typeof queueName != 'string') return queueName;
if(!this.instances[queueName])
this.instances[queueName] = new Effect.ScopedQueue();
return this.instances[queueName];
}
}
Effect.Queue = Effect.Queues.get('global');
Effect.DefaultOptions = {
transition: Effect.Transitions.sinoidal,
duration:   1.0,   // seconds
fps:        60.0,  // max. 60fps due to Effect.Queue implementation
sync:       false, // true for combining
from:       0.0,
to:         1.0,
delay:      0.0,
queue:      'parallel'
}
Effect.Base = function() {};
Effect.Base.prototype = {
position: null,
start: function(options) {
this.options      = Object.extend(Object.extend({},Effect.DefaultOptions), options || {});
this.currentFrame = 0;
this.state        = 'idle';
this.startOn      = this.options.delay*1000;
this.finishOn     = this.startOn + (this.options.duration*1000);
this.event('beforeStart');
if(!this.options.sync)
Effect.Queues.get(typeof this.options.queue == 'string' ?
'global' : this.options.queue.scope).add(this);
},
loop: function(timePos) {
if(timePos >= this.startOn) {
if(timePos >= this.finishOn) {
this.render(1.0);
this.cancel();
this.event('beforeFinish');
if(this.finish) this.finish();
this.event('afterFinish');
return;
}
var pos   = (timePos - this.startOn) / (this.finishOn - this.startOn);
var frame = Math.round(pos * this.options.fps * this.options.duration);
if(frame > this.currentFrame) {
this.render(pos);
this.currentFrame = frame;
}
}
},
render: function(pos) {
if(this.state == 'idle') {
this.state = 'running';
this.event('beforeSetup');
if(this.setup) this.setup();
this.event('afterSetup');
}
if(this.state == 'running') {
if(this.options.transition) pos = this.options.transition(pos);
pos *= (this.options.to-this.options.from);
pos += this.options.from;
this.position = pos;
this.event('beforeUpdate');
if(this.update) this.update(pos);
this.event('afterUpdate');
}
},
cancel: function() {
if(!this.options.sync)
Effect.Queues.get(typeof this.options.queue == 'string' ?
'global' : this.options.queue.scope).remove(this);
this.state = 'finished';
},
event: function(eventName) {
if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
if(this.options[eventName]) this.options[eventName](this);
},
inspect: function() {
var data = $H();
for(property in this)
if(typeof this[property] != 'function') data[property] = this[property];
return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
}
}
Effect.Parallel = Class.create();
Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), {
initialize: function(effects) {
this.effects = effects || [];
this.start(arguments[1]);
},
update: function(position) {
this.effects.invoke('render', position);
},
finish: function(position) {
this.effects.each( function(effect) {
effect.render(1.0);
effect.cancel();
effect.event('beforeFinish');
if(effect.finish) effect.finish(position);
effect.event('afterFinish');
});
}
});
Effect.Event = Class.create();
Object.extend(Object.extend(Effect.Event.prototype, Effect.Base.prototype), {
initialize: function() {
var options = Object.extend({
duration: 0
}, arguments[0] || {});
this.start(options);
},
update: Prototype.emptyFunction
});
Effect.Opacity = Class.create();
Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
initialize: function(element) {
this.element = $(element);
if(!this.element) throw(Effect._elementDoesNotExistError);
if(/MSIE/.test(navigator.userAgent) && !window.opera && (!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom: 1});
var options = Object.extend({
from: this.element.getOpacity() || 0.0,
to:   1.0
}, arguments[1] || {});
this.start(options);
},
update: function(position) {
this.element.setOpacity(position);
}
});
Effect.Move = Class.create();
Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), {
initialize: function(element) {
this.element = $(element);
if(!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({
x:    0,
y:    0,
mode: 'relative'
}, arguments[1] || {});
this.start(options);
},
setup: function() {
this.element.makePositioned();
this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
this.originalTop  = parseFloat(this.element.getStyle('top')  || '0');
if(this.options.mode == 'absolute') {
this.options.x = this.options.x - this.originalLeft;
this.options.y = this.options.y - this.originalTop;
}
},
update: function(position) {
this.element.setStyle({
left: Math.round(this.options.x  * position + this.originalLeft) + 'px',
top:  Math.round(this.options.y  * position + this.originalTop)  + 'px'
});
}
});
Effect.MoveBy = function(element, toTop, toLeft) {
return new Effect.Move(element,
Object.extend({ x: toLeft, y: toTop }, arguments[3] || {}));
};
Effect.Scale = Class.create();
Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
initialize: function(element, percent) {
this.element = $(element);
if(!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({
scaleX: true,
scaleY: true,
scaleContent: true,
scaleFromCenter: false,
scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
scaleFrom: 100.0,
scaleTo:   percent
}, arguments[2] || {});
this.start(options);
},
setup: function() {
this.restoreAfterFinish = this.options.restoreAfterFinish || false;
this.elementPositioning = this.element.getStyle('position');
this.originalStyle = {};
['top','left','width','height','fontSize'].each( function(k) {
this.originalStyle[k] = this.element.style[k];
}.bind(this));
this.originalTop  = this.element.offsetTop;
this.originalLeft = this.element.offsetLeft;
var fontSize = this.element.getStyle('font-size') || '100%';
['em','px','%','pt'].each( function(fontSizeType) {
if(fontSize.indexOf(fontSizeType)>0) {
this.fontSize     = parseFloat(fontSize);
this.fontSizeType = fontSizeType;
}
}.bind(this));
this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
this.dims = null;
if(this.options.scaleMode=='box')
this.dims = [this.element.offsetHeight, this.element.offsetWidth];
if(/^content/.test(this.options.scaleMode))
this.dims = [this.element.scrollHeight, this.element.scrollWidth];
if(!this.dims)
this.dims = [this.options.scaleMode.originalHeight,
this.options.scaleMode.originalWidth];
},
update: function(position) {
var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
if(this.options.scaleContent && this.fontSize)
this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
},
finish: function(position) {
if(this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
},
setDimensions: function(height, width) {
var d = {};
if(this.options.scaleX) d.width = Math.round(width) + 'px';
if(this.options.scaleY) d.height = Math.round(height) + 'px';
if(this.options.scaleFromCenter) {
var topd  = (height - this.dims[0])/2;
var leftd = (width  - this.dims[1])/2;
if(this.elementPositioning == 'absolute') {
if(this.options.scaleY) d.top = this.originalTop-topd + 'px';
if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
} else {
if(this.options.scaleY) d.top = -topd + 'px';
if(this.options.scaleX) d.left = -leftd + 'px';
}
}
this.element.setStyle(d);
}
});
Effect.Highlight = Class.create();
Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), {
initialize: function(element) {
this.element = $(element);
if(!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
this.start(options);
},
setup: function() {
if(this.element.getStyle('display')=='none') { this.cancel(); return; }
this.oldStyle = {};
if (!this.options.keepBackgroundImage) {
this.oldStyle.backgroundImage = this.element.getStyle('background-image');
this.element.setStyle({backgroundImage: 'none'});
}
if(!this.options.endcolor)
this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
if(!this.options.restorecolor)
this.options.restorecolor = this.element.getStyle('background-color');
this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
},
update: function(position) {
this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
},
finish: function() {
this.element.setStyle(Object.extend(this.oldStyle, {
backgroundColor: this.options.restorecolor
}));
}
});
Effect.ScrollTo = Class.create();
Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), {
initialize: function(element) {
this.element = $(element);
this.start(arguments[1] || {});
},
setup: function() {
Position.prepare();
var offsets = Position.cumulativeOffset(this.element);
if(this.options.offset) offsets[1] += this.options.offset;
var max = window.innerHeight ?
window.height - window.innerHeight :
document.body.scrollHeight -
(document.documentElement.clientHeight ?
document.documentElement.clientHeight : document.body.clientHeight);
this.scrollStart = Position.deltaY;
this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart;
},
update: function(position) {
Position.prepare();
window.scrollTo(Position.deltaX,
this.scrollStart + (position*this.delta));
}
});
/* ------------- combination effects ------------- */
Effect.Fade = function(element) {
element = $(element);
var oldOpacity = element.getInlineOpacity();
var options = Object.extend({
from: element.getOpacity() || 1.0,
to:   0.0,
afterFinishInternal: function(effect) {
if(effect.options.to!=0) return;
effect.element.hide().setStyle({opacity: oldOpacity});
}}, arguments[1] || {});
return new Effect.Opacity(element,options);
}
Effect.Appear = function(element) {
element = $(element);
var options = Object.extend({
from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
to:   1.0,
afterFinishInternal: function(effect) {
effect.element.forceRerendering();
},
beforeSetup: function(effect) {
effect.element.setOpacity(effect.options.from).show();
}}, arguments[1] || {});
return new Effect.Opacity(element,options);
}
Effect.Puff = function(element) {
element = $(element);
var oldStyle = {
opacity: element.getInlineOpacity(),
position: element.getStyle('position'),
top:  element.style.top,
left: element.style.left,
width: element.style.width,
height: element.style.height
};
return new Effect.Parallel(
[ new Effect.Scale(element, 200,
{ sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
Object.extend({ duration: 1.0,
beforeSetupInternal: function(effect) {
Position.absolutize(effect.effects[0].element)
},
afterFinishInternal: function(effect) {
effect.effects[0].element.hide().setStyle(oldStyle); }
}, arguments[1] || {})
);
}
Effect.BlindUp = function(element) {
element = $(element);
element.makeClipping();
return new Effect.Scale(element, 0,
Object.extend({ scaleContent: false,
scaleX: false,
restoreAfterFinish: true,
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping();
}
}, arguments[1] || {})
);
}
Effect.BlindDown = function(element) {
element = $(element);
var elementDimensions = element.getDimensions();
return new Effect.Scale(element, 100, Object.extend({
scaleContent: false,
scaleX: false,
scaleFrom: 0,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
afterSetup: function(effect) {
effect.element.makeClipping().setStyle({height: '0px'}).show();
},
afterFinishInternal: function(effect) {
effect.element.undoClipping();
}
}, arguments[1] || {}));
}
Effect.SwitchOff = function(element) {
element = $(element);
var oldOpacity = element.getInlineOpacity();
return new Effect.Appear(element, Object.extend({
duration: 0.4,
from: 0,
transition: Effect.Transitions.flicker,
afterFinishInternal: function(effect) {
new Effect.Scale(effect.element, 1, {
duration: 0.3, scaleFromCenter: true,
scaleX: false, scaleContent: false, restoreAfterFinish: true,
beforeSetup: function(effect) {
effect.element.makePositioned().makeClipping();
},
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
}
})
}
}, arguments[1] || {}));
}
Effect.DropOut = function(element) {
element = $(element);
var oldStyle = {
top: element.getStyle('top'),
left: element.getStyle('left'),
opacity: element.getInlineOpacity() };
return new Effect.Parallel(
[ new Effect.Move(element, {x: 0, y: 100, sync: true }),
new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
Object.extend(
{ duration: 0.5,
beforeSetup: function(effect) {
effect.effects[0].element.makePositioned();
},
afterFinishInternal: function(effect) {
effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
}
}, arguments[1] || {}));
}
Effect.Shake = function(element) {
element = $(element);
var oldStyle = {
top: element.getStyle('top'),
left: element.getStyle('left') };
return new Effect.Move(element,
{ x:  20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
effect.element.undoPositioned().setStyle(oldStyle);
}}) }}) }}) }}) }}) }});
}
Effect.SlideDown = function(element) {
element = $(element).cleanWhitespace();
var oldInnerBottom = element.down().getStyle('bottom');
var elementDimensions = element.getDimensions();
return new Effect.Scale(element, 100, Object.extend({
scaleContent: false,
scaleX: false,
scaleFrom: window.opera ? 0 : 1,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
afterSetup: function(effect) {
effect.element.makePositioned();
effect.element.down().makePositioned();
if(window.opera) effect.element.setStyle({top: ''});
effect.element.makeClipping().setStyle({height: '0px'}).show();
},
afterUpdateInternal: function(effect) {
effect.element.down().setStyle({bottom:
(effect.dims[0] - effect.element.clientHeight) + 'px' });
},
afterFinishInternal: function(effect) {
effect.element.undoClipping().undoPositioned();
effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
}, arguments[1] || {})
);
}
Effect.SlideUp = function(element) {
element = $(element).cleanWhitespace();
var oldInnerBottom = element.down().getStyle('bottom');
return new Effect.Scale(element, window.opera ? 0 : 1,
Object.extend({ scaleContent: false,
scaleX: false,
scaleMode: 'box',
scaleFrom: 100,
restoreAfterFinish: true,
beforeStartInternal: function(effect) {
effect.element.makePositioned();
effect.element.down().makePositioned();
if(window.opera) effect.element.setStyle({top: ''});
effect.element.makeClipping().show();
},
afterUpdateInternal: function(effect) {
effect.element.down().setStyle({bottom:
(effect.dims[0] - effect.element.clientHeight) + 'px' });
},
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping().undoPositioned().setStyle({bottom: oldInnerBottom});
effect.element.down().undoPositioned();
}
}, arguments[1] || {})
);
}
Effect.Squish = function(element) {
return new Effect.Scale(element, window.opera ? 1 : 0, {
restoreAfterFinish: true,
beforeSetup: function(effect) {
effect.element.makeClipping();
},
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping();
}
});
}
Effect.Grow = function(element) {
element = $(element);
var options = Object.extend({
direction: 'center',
moveTransition: Effect.Transitions.sinoidal,
scaleTransition: Effect.Transitions.sinoidal,
opacityTransition: Effect.Transitions.full
}, arguments[1] || {});
var oldStyle = {
top: element.style.top,
left: element.style.left,
height: element.style.height,
width: element.style.width,
opacity: element.getInlineOpacity() };
var dims = element.getDimensions();
var initialMoveX, initialMoveY;
var moveX, moveY;
switch (options.direction) {
case 'top-left':
initialMoveX = initialMoveY = moveX = moveY = 0;
break;
case 'top-right':
initialMoveX = dims.width;
initialMoveY = moveY = 0;
moveX = -dims.width;
break;
case 'bottom-left':
initialMoveX = moveX = 0;
initialMoveY = dims.height;
moveY = -dims.height;
break;
case 'bottom-right':
initialMoveX = dims.width;
initialMoveY = dims.height;
moveX = -dims.width;
moveY = -dims.height;
break;
case 'center':
initialMoveX = dims.width / 2;
initialMoveY = dims.height / 2;
moveX = -dims.width / 2;
moveY = -dims.height / 2;
break;
}
return new Effect.Move(element, {
x: initialMoveX,
y: initialMoveY,
duration: 0.01,
beforeSetup: function(effect) {
effect.element.hide().makeClipping().makePositioned();
},
afterFinishInternal: function(effect) {
new Effect.Parallel(
[ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
new Effect.Scale(effect.element, 100, {
scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
], Object.extend({
beforeSetup: function(effect) {
effect.effects[0].element.setStyle({height: '0px'}).show();
},
afterFinishInternal: function(effect) {
effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
}
}, options)
)
}
});
}
Effect.Shrink = function(element) {
element = $(element);
var options = Object.extend({
direction: 'center',
moveTransition: Effect.Transitions.sinoidal,
scaleTransition: Effect.Transitions.sinoidal,
opacityTransition: Effect.Transitions.none
}, arguments[1] || {});
var oldStyle = {
top: element.style.top,
left: element.style.left,
height: element.style.height,
width: element.style.width,
opacity: element.getInlineOpacity() };
var dims = element.getDimensions();
var moveX, moveY;
switch (options.direction) {
case 'top-left':
moveX = moveY = 0;
break;
case 'top-right':
moveX = dims.width;
moveY = 0;
break;
case 'bottom-left':
moveX = 0;
moveY = dims.height;
break;
case 'bottom-right':
moveX = dims.width;
moveY = dims.height;
break;
case 'center':
moveX = dims.width / 2;
moveY = dims.height / 2;
break;
}
return new Effect.Parallel(
[ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
], Object.extend({
beforeStartInternal: function(effect) {
effect.effects[0].element.makePositioned().makeClipping();
},
afterFinishInternal: function(effect) {
effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
}, options)
);
}
Effect.Pulsate = function(element) {
element = $(element);
var options    = arguments[1] || {};
var oldOpacity = element.getInlineOpacity();
var transition = options.transition || Effect.Transitions.sinoidal;
var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
reverser.bind(transition);
return new Effect.Opacity(element,
Object.extend(Object.extend({  duration: 2.0, from: 0,
afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
}, options), {transition: reverser}));
}
Effect.Fold = function(element) {
element = $(element);
var oldStyle = {
top: element.style.top,
left: element.style.left,
width: element.style.width,
height: element.style.height };
element.makeClipping();
return new Effect.Scale(element, 5, Object.extend({
scaleContent: false,
scaleX: false,
afterFinishInternal: function(effect) {
new Effect.Scale(element, 1, {
scaleContent: false,
scaleY: false,
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping().setStyle(oldStyle);
} });
}}, arguments[1] || {}));
};
Effect.Morph = Class.create();
Object.extend(Object.extend(Effect.Morph.prototype, Effect.Base.prototype), {
initialize: function(element) {
this.element = $(element);
if(!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({
style: {}
}, arguments[1] || {});
if (typeof options.style == 'string') {
if(options.style.indexOf(':') == -1) {
var cssText = '', selector = '.' + options.style;
$A(document.styleSheets).reverse().each(function(styleSheet) {
if (styleSheet.cssRules) cssRules = styleSheet.cssRules;
else if (styleSheet.rules) cssRules = styleSheet.rules;
$A(cssRules).reverse().each(function(rule) {
if (selector == rule.selectorText) {
cssText = rule.style.cssText;
throw $break;
}
});
if (cssText) throw $break;
});
this.style = cssText.parseStyle();
options.afterFinishInternal = function(effect){
effect.element.addClassName(effect.options.style);
effect.transforms.each(function(transform) {
if(transform.style != 'opacity')
effect.element.style[transform.style.camelize()] = '';
});
}
} else this.style = options.style.parseStyle();
} else this.style = $H(options.style)
this.start(options);
},
setup: function(){
function parseColor(color){
if(!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
color = color.parseColor();
return $R(0,2).map(function(i){
return parseInt( color.slice(i*2+1,i*2+3), 16 )
});
}
this.transforms = this.style.map(function(pair){
var property = pair[0].underscore().dasherize(), value = pair[1], unit = null;
if(value.parseColor('#zzzzzz') != '#zzzzzz') {
value = value.parseColor();
unit  = 'color';
} else if(property == 'opacity') {
value = parseFloat(value);
if(/MSIE/.test(navigator.userAgent) && !window.opera && (!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom: 1});
} else if(Element.CSS_LENGTH.test(value))
var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/),
value = parseFloat(components[1]), unit = (components.length == 3) ? components[2] : null;
var originalValue = this.element.getStyle(property);
return $H({
style: property,
originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
targetValue: unit=='color' ? parseColor(value) : value,
unit: unit
});
}.bind(this)).reject(function(transform){
return (
(transform.originalValue == transform.targetValue) ||
(
transform.unit != 'color' &&
(isNaN(transform.originalValue) || isNaN(transform.targetValue))
)
)
});
},
update: function(position) {
var style = $H(), value = null;
this.transforms.each(function(transform){
value = transform.unit=='color' ?
$R(0,2).inject('#',function(m,v,i){
return m+(Math.round(transform.originalValue[i]+
(transform.targetValue[i] - transform.originalValue[i])*position)).toColorPart() }) :
transform.originalValue + Math.round(
((transform.targetValue - transform.originalValue) * position) * 1000)/1000 + transform.unit;
style[transform.style] = value;
});
this.element.setStyle(style);
}
});
Effect.Transform = Class.create();
Object.extend(Effect.Transform.prototype, {
initialize: function(tracks){
this.tracks  = [];
this.options = arguments[1] || {};
this.addTracks(tracks);
},
addTracks: function(tracks){
tracks.each(function(track){
var data = $H(track).values().first();
this.tracks.push($H({
ids:     $H(track).keys().first(),
effect:  Effect.Morph,
options: { style: data }
}));
}.bind(this));
return this;
},
play: function(){
return new Effect.Parallel(
this.tracks.map(function(track){
var elements = [$(track.ids) || $$(track.ids)].flatten();
return elements.map(function(e){ return new track.effect(e, Object.extend({ sync:true }, track.options)) });
}).flatten(),
this.options
);
}
});
Element.CSS_PROPERTIES = $w(
'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
'fontSize fontWeight height left letterSpacing lineHeight ' +
'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
'right textIndent top width wordSpacing zIndex');
Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
String.prototype.parseStyle = function(){
var element = Element.extend(document.createElement('div'));
element.innerHTML = '<div style="' + this + '"></div>';
var style = element.down().style, styleRules = $H();
Element.CSS_PROPERTIES.each(function(property){
if(style[property]) styleRules[property] = style[property];
});
if(/MSIE/.test(navigator.userAgent) && !window.opera && this.indexOf('opacity') > -1) {
styleRules.opacity = this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1];
}
return styleRules;
};
Element.morph = function(element, style) {
new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || {}));
return element;
};
['setOpacity','getOpacity','getInlineOpacity','forceRerendering','setContentZoom',
'collectTextNodes','collectTextNodesIgnoreClass','morph'].each(
function(f) { Element.Methods[f] = Element[f]; }
);
Element.Methods.visualEffect = function(element, effect, options) {
s = effect.gsub(/_/, '-').camelize();
effect_class = s.charAt(0).toUpperCase() + s.substring(1);
new Effect[effect_class](element, options);
return $(element);
};
Element.addMethods();
/**
* SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
*
* SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
*/
if(typeof deconcept == "undefined") var deconcept = new Object();
if(typeof deconcept.util == "undefined") deconcept.util = new Object();
if(typeof deconcept.SWFObjectUtil == "undefined") deconcept.SWFObjectUtil = new Object();
deconcept.SWFObject = function(swf, id, w, h, ver, c, quality, xiRedirectUrl, redirectUrl, detectKey) {
if (!document.getElementById) { return; }
this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params = new Object();
this.variables = new Object();
this.attributes = new Array();
if(swf) { this.setAttribute('swf', swf); }
if(id) { this.setAttribute('id', id); }
if(w) { this.setAttribute('width', w); }
if(h) { this.setAttribute('height', h); }
if(ver) { this.setAttribute('version', new deconcept.PlayerVersion(ver.toString().split("."))); }
this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion();
if (!window.opera && document.all && this.installedVer.major > 7) {
deconcept.SWFObject.doPrepUnload = true;
}
if(c) { this.addParam('bgcolor', c); }
var q = quality ? quality : 'high';
this.addParam('quality', q);
this.setAttribute('useExpressInstall', false);
this.setAttribute('doExpressInstall', false);
var xir = (xiRedirectUrl) ? xiRedirectUrl : window.location;
this.setAttribute('xiRedirectUrl', xir);
this.setAttribute('redirectUrl', '');
if(redirectUrl) { this.setAttribute('redirectUrl', redirectUrl); }
}
deconcept.SWFObject.prototype = {
useExpressInstall: function(path) {
this.xiSWFPath = !path ? "expressinstall.swf" : path;
this.setAttribute('useExpressInstall', true);
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
getAttribute: function(name){
return this.attributes[name];
},
addParam: function(name, value){
this.params[name] = value;
},
getParams: function(){
return this.params;
},
addVariable: function(name, value){
this.variables[name] = value;
},
getVariable: function(name){
return this.variables[name];
},
getVariables: function(){
return this.variables;
},
getVariablePairs: function(){
var variablePairs = new Array();
var key;
var variables = this.getVariables();
for(key in variables){
variablePairs[variablePairs.length] = key +"="+ variables[key];
}
return variablePairs;
},
getSWFHTML: function() {
var swfNode = "";
if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
if (this.getAttribute("doExpressInstall")) {
this.addVariable("MMplayerType", "PlugIn");
this.setAttribute('swf', this.xiSWFPath);
}
swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" wmode="transparent" style="'+ this.getAttribute('style') +'"';
swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
var params = this.getParams();
for(var key in params){ swfNode += [key] +'="'+ params[key] +'" '; }
var pairs = this.getVariablePairs().join("&");
if (pairs.length > 0){ swfNode += 'flashvars="'+ pairs +'"'; }
swfNode += '/>';
} else { // PC IE
if (this.getAttribute("doExpressInstall")) {
this.addVariable("MMplayerType", "ActiveX");
this.setAttribute('swf', this.xiSWFPath);
}
swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ this.getAttribute('style') +'">';
swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
var params = this.getParams();
for(var key in params) {
swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
}
var pairs = this.getVariablePairs().join("&");
if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
swfNode += '<param name="wmode" value="transparent" />';
swfNode += "</object>";
}
return swfNode;
},
write: function(elementId){
if(this.getAttribute('useExpressInstall')) {
var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
this.setAttribute('doExpressInstall', true);
this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
document.title = document.title.slice(0, 47) + " - Flash Player Installation";
this.addVariable("MMdoctitle", document.title);
}
}
if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
n.innerHTML = this.getSWFHTML();
return true;
}else{
if(this.getAttribute('redirectUrl') != "") {
document.location.replace(this.getAttribute('redirectUrl'));
}
}
return false;
}
}
/* ---- detection functions ---- */
deconcept.SWFObjectUtil.getPlayerVersion = function(){
var PlayerVersion = new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins && navigator.mimeTypes.length){
var x = navigator.plugins["Shockwave Flash"];
if(x && x.description) {
PlayerVersion = new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
}
}else if (navigator.userAgent && navigator.userAgent.indexOf("Windows CE") >= 0){ // if Windows CE
var axo = 1;
var counter = 3;
while(axo) {
try {
counter++;
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+ counter);
PlayerVersion = new deconcept.PlayerVersion([counter,0,0]);
} catch (e) {
axo = null;
}
}
} else { // Win IE (non mobile)
try{
var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
}catch(e){
try {
var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
PlayerVersion = new deconcept.PlayerVersion([6,0,21]);
axo.AllowScriptAccess = "always"; // error if player version < 6.0.47 (thanks to Michael Williams @ Adobe for this code)
} catch(e) {
if (PlayerVersion.major == 6) {
return PlayerVersion;
}
}
try {
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
} catch(e) {}
}
if (axo != null) {
PlayerVersion = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
}
}
return PlayerVersion;
}
deconcept.PlayerVersion = function(arrVersion){
this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
}
deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
if(this.major < fv.major) return false;
if(this.major > fv.major) return true;
if(this.minor < fv.minor) return false;
if(this.minor > fv.minor) return true;
if(this.rev < fv.rev) return false;
return true;
}
/* ---- get value of query string param ---- */
deconcept.util = {
getRequestParameter: function(param) {
var q = document.location.search || document.location.hash;
if (param == null) { return q; }
if(q) {
var pairs = q.substring(1).split("&");
for (var i=0; i < pairs.length; i++) {
if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
return pairs[i].substring((pairs[i].indexOf("=")+1));
}
}
}
return "";
}
}
/* fix for video streaming bug */
deconcept.SWFObjectUtil.cleanupSWFs = function() {
var objects = document.getElementsByTagName("OBJECT");
for (var i = objects.length - 1; i >= 0; i--) {
objects[i].style.display = 'none';
for (var x in objects[i]) {
if (typeof objects[i][x] == 'function') {
objects[i][x] = function(){};
}
}
}
}
if (deconcept.SWFObject.doPrepUnload) {
if (!deconcept.unloadSet) {
deconcept.SWFObjectUtil.prepUnload = function() {
__flash_unloadHandler = function(){};
__flash_savedUnloadHandler = function(){};
window.attachEvent("onunload", deconcept.SWFObjectUtil.cleanupSWFs);
}
window.attachEvent("onbeforeunload", deconcept.SWFObjectUtil.prepUnload);
deconcept.unloadSet = true;
}
}
/* add document.getElementById if needed (mobile IE < 5) */
if (!document.getElementById && document.all) { document.getElementById = function(id) { return document.all[id]; }}
/* add some aliases for ease of use/backwards compatibility */
var getQueryParamValue = deconcept.util.getRequestParameter;
var FlashObject = deconcept.SWFObject; // for legacy support
var SWFObject = deconcept.SWFObject;
var layouts = {};
layouts.modLiveStream = {};
layouts.modControls = {};
layouts.modControls['modControls.lo'] = 'var outControls="";\n'+
'var outFullscreen="";\n'+
'var outCloseFullscreen="";\n'+
'// Write handle\n'+
'\n'+
'if (this.module.config.playerHasPlayPause == \'yes\') {\n'+
'	outControls += this.runTemplate("playPause");\n'+
'}\n'+
'\n'+
'\n'+
'if (this.module.config.playerCanSkip == \'yes\') {\n'+
'	\n'+
'	outControls += this.runTemplate("skip");\n'+
'}\n'+
'\n'+
'\n'+
'if (this.module.config.playerHasProgressbar == \'yes\') {\n'+
'	outControls += this.runTemplate("progressbar");\n'+
'}\n'+
'\n'+
'outControls += this.runTemplate("playerTime");\n'+
'\n'+
'outControls += this.runTemplate("fullscreen");\n'+
'\n'+
'if (this.module.config.playerHasVolumebar == \'yes\') {\n'+
'	outControls += this.runTemplate("volume");\n'+
'}\n'+
'\n'+
'\n'+
'outControls += this.runTemplate("playerData");\n'+
'\n'+
'this.output(outControls,this.module.config.playerControlsContainerId);\n'+
'\n'+
'this.showSeekbar = function(cond) {\n'+
'\n'+
'	if (this.module.config.playerHasProgressbar == \'yes\') {\n'+
'		document.getElementById(this.module.__parent.config.modControls.playerProgressbarId).style.visibility = cond;\n'+
'		document.getElementById(\'playerHandle2\').style.visibility = cond;\n'+
'	}\n'+
'\n'+
'}\n'+
'\n'+
'this.setState = function(state) {\n'+
'	\n'+
'	var template;\n'+
'	if (state==1)\n'+
'		template = this.runTemplate("playButton");\n'+
'	if (state==0)\n'+
'		template = this.runTemplate("pauseButton");\n'+
'\n'+
'	if (template == undefined)\n'+
'		return;\n'+
'\n'+
'	this.output(template,this.module.config.playerPlayPauseContainerId);\n'+
'}\n'+
'\n'+
'this.setState(0);\n'+
'\n'+
'// Volume START\n'+
'\n'+
'	\n'+
'\n'+
'this.volumeHandleDragging = false;\n'+
'\n'+
'\n'+
'// Volume plus/minus buttons\n'+
'\n'+
'this.goVolume = function(inc) {\n'+
'	\n'+
'	var volumeCookie = parseInt(this.module.__parent.config.COOKIE[\'volume\']);\n'+
'	\n'+
'	var posPct = (100-(volumeCookie+inc))/100;\n'+
'	\n'+
'	var savePos = Math.ceil(100-(posPct*100));\n'+
'	\n'+
'	if ( (savePos) > 100)\n'+
'		savePos = 100;\n'+
'	if ( (savePos) < 0)\n'+
'		savePos = 0;\n'+
'	\n'+
'	\n'+
'	try {\n'+
'		this.module.__parent.player.handler.setVolumePct(savePos);\n'+
'		\n'+
'	}\n'+
'	catch(e){\n'+
'		// No need to catch any exceptions..\n'+
'		\n'+
'	}\n'+
'	try {\n'+
'		this.module.__parent.cookies.saveCookie("volume",savePos);\n'+
'	}\n'+
'	catch(e){\n'+
'		\n'+
'		// No need to catch any exceptions..\n'+
'	}\n'+
'}\n'+
'\n'+
'/*\n'+
'var volPlus = document.getElementById(this.module.config.playerVolumePlusId);\n'+
'var volMinus = document.getElementById(this.module.config.playerVolumeMinusId);\n'+
'\n'+
'volPlus.onclick = function() {\n'+
'	this.goVolume(10);\n'+
'}\n'+
'\n'+
'\n'+
'volMinus.onclick = function() {\n'+
'	this.goVolume(-10);\n'+
'}*/\n'+
'\n'+
'\n'+
'// Volume END\n'+
'\n'+
'\n'+
'\n'+
'// Create progressbar drag\'n\'drop functionality\n'+
'if (this.module.config.playerHasProgressbar == \'yes\') {\n'+
'	\n'+
'	\n'+
'	\n'+
'	try {\n'+
'	\n'+
'	var playerProgressBar = document.getElementById(this.module.config.playerProgressbarId);\n'+
'	var playerHandle = document.getElementById(this.module.config.playerProgressbarHandleId);\n'+
'\n'+
'	\n'+
'	this.isDragging = false;\n'+
'\n'+
'\n'+
'	var progressBarWidth = parseInt(playerProgressBar.offsetWidth);\n'+
'	\n'+
'	\n'+
'	var playerTime = document.getElementById(\'playerTime\');\n'+
'	\n'+
'	\n'+
'	\n'+
'	// Clone time div.\n'+
'	//var timeC = document.createElement(\'div\');\n'+
'	//var playerHC = document.createElement(\'img\');\n'+
'	\n'+
'	\n'+
'	var timeC = playerTime.cloneNode(true);\n'+
'	var playerHC = playerHandle.cloneNode(true);\n'+
'	\n'+
'	\n'+
'	timeC.id = \'playerTime2\';\n'+
'	playerHC.id = \'playerHandle2\';\n'+
'	\n'+
'\n'+
'	\n'+
'	// Clone seek handle div.\n'+
'	\n'+
'	\n'+
'	document.body.appendChild(timeC);\n'+
'	document.body.appendChild(playerHC);\n'+
'	\n'+
'	\n'+
'	\n'+
'	var playerHandle = document.getElementById(\'playerHandle\');\n'+
'	var playerHC = document.getElementById(\'playerHandle2\');\n'+
'	var timeC = document.getElementById(\'playerTime2\');\n'+
'	var playerTime = document.getElementById(\'playerTime\');\n'+
'	\n'+
'	hp = Toolbox.element.getPos(playerHandle);\n'+
'	\n'+
'	playerHC.style.left = (hp.x+playerHandle.offsetLeft)+\'px\';\n'+
'	playerHC.style.top = (hp.y+playerHandle.offsetTop)+\'px\';\n'+
'	\n'+
'	timeC.style.left = playerTime.offsetLeft+\'px\';\n'+
'	timeC.style.top = playerTime.offsetTop+\'px\'\n'+
'	\n'+
'\n'+
'	playerHC.style.position = \'absolute\';\n'+
'	playerHC.style.zIndex = \'999\';\n'+
'	timeC.style.position = \'absolute\';\n'+
'	\n'+
'	\n'+
'	\n'+
'\n'+
'	var playerHandle2 = document.getElementById(\'playerHandle2\');\n'+
'	var playerTime2 = document.getElementById(\'playerTime2\');\n'+
'	\n'+
'	playerHandle.style.visibility = \'hidden\';\n'+
'	\n'+
'	var handleWidth = parseInt(playerHandle2.offsetWidth);\n'+
'\n'+
'\n'+
'	}\n'+
'	catch(e){ }\n'+
'	\n'+
'	playerProgressBar.ref = this;\n'+
'	\n'+
'	playerProgressBar.onclick = function(e) {\n'+
'		\n'+
'		try {\n'+
'			\n'+
'			\n'+
'			var tempX,tempY;\n'+
'		\n'+
'			// grab the x-y pos if browser supports clientX/Y\n'+
'			\n'+
'			var cursor = Toolbox.mouse.getCursor(e);\n'+
'			\n'+
'			tempX = cursor.x;\n'+
'			tempY = cursor.y;\n'+
'		\n'+
'			var trueXClick = tempX - this.offsetLeft;\n'+
'			\n'+
'			var progressBarWidth = parseInt(playerProgressBar.offsetWidth);\n'+
'			var handleWidth = parseInt(playerHandle2.offsetWidth);\n'+
'			var time_total = this.ref.module.__parent.player.handler.getTotalSeconds();	\n'+
'			var offset_time = Math.ceil((trueXClick/(progressBarWidth-handleWidth))*time_total);\n'+
'			\n'+
'			var handleXPos = trueXClick+hp.x;\n'+
'			if (!handleXPos)\n'+
'				handleXPos = hp.x;\n'+
'				\n'+
'	\n'+
'			playerHandle2.style.left = handleXPos+"px";	\n'+
'		\n'+
'			this.ref.module.__parent.player.handler.seek(offset_time);\n'+
'			this.ref.module.__parent.player.handler.setPlaystate(1);\n'+
'			\n'+
'			}\n'+
'			catch (e) {\n'+
'				//alert("err:"+e);\n'+
'				// No need to catch any exceptions\n'+
'			}\n'+
'	}\n'+
'	\n'+
'	\n'+
'	\n'+
'	\n'+
'	this.updateSeekhandle = function(time_played,time_total) {\n'+
'\n'+
'		if (this.isDragging == true)\n'+
'			return;\n'+
'		\n'+
'		var offset;\n'+
'		var progressBarWidth = playerProgressBar.offsetWidth;\n'+
'		\n'+
'		// Get the width of the bar, minus the width of the handle.\n'+
'		var barW = (progressBarWidth-handleWidth);\n'+
'		\n'+
'		// If barW didnt evaluate, 0 it.\n'+
'		if (!barW || isNaN(barW))\n'+
'			barW = 0;\n'+
'		\n'+
'		// Calculate offset\n'+
'		\n'+
'		var handleOffset = Math.round((time_played/time_total)*barW)+"px";\n'+
'		\n'+
'		if (!handleOffset)\n'+
'			handleOffset = 0;\n'+
'		// Calculate time\n'+
'		var timeStr = this.module.getTime(time_played,time_total);\n'+
'		\n'+
'		// Don\'t show any progress if time played is 0.\n'+
'\n'+
'		//if (time_played>=0) {\n'+
'		\n'+
'			playerTime2.innerHTML = timeStr;\n'+
'			\n'+
'			var posX = parseInt(hp.x)+parseInt(handleOffset);\n'+
'			\n'+
'			if ( posX < hp.x || posX > (hp.x + progressBarWidth) || !posX || posX == 0)\n'+
'				return;\n'+
'			\n'+
'			playerHandle2.style.left = posX+"px";\n'+
'		\n'+
'		//}\n'+
'		\n'+
'	}\n'+
'	\n'+
'	Drag.init(playerHandle2, null, hp.x, (hp.x+(playerProgressBar.offsetWidth-playerHandle2.offsetWidth)), hp.y, hp.y);\n'+
'	\n'+
'	playerHandle2.ref = this;\n'+
'	\n'+
'	playerHandle2.onDragStart = function() {\n'+
'\n'+
'		try {\n'+
'		\n'+
'		this.ref.module.__parent.player.handler.setPlaystate(0);\n'+
'		}\n'+
'		catch(e) {\n'+
'			//alert("err:"+e);\n'+
'			// No need to catch any exceptions\n'+
'		}\n'+
'		\n'+
'		this.ref.isDragging = true;\n'+
'\n'+
'	}\n'+
'	\n'+
'	playerHandle2.onDrag = function(x,y) {\n'+
'		\n'+
'\n'+
'		this.ref.isDragging = true;\n'+
'		\n'+
'		var time_total;\n'+
'		var time_played;\n'+
'		\n'+
'		x = x-hp.x;\n'+
'		\n'+
'		try {\n'+
'			var progressBarWidth = parseInt(playerProgressBar.offsetWidth);\n'+
'			var handleWidth = parseInt(playerHandle2.offsetWidth);\n'+
'			time_total = this.ref.module.__parent.player.handler.getTotalSeconds();	\n'+
'			time_played = this.ref.module.__parent.player.handler.getPlayedSeconds();	\n'+
'			\n'+
'			var offset_time = (x/(progressBarWidth-handleWidth))*time_total;\n'+
'			\n'+
'			\n'+
'		}\n'+
'		catch(e) {\n'+
'			//alert("err:"+e);\n'+
'			// No need to catch any exceptions\n'+
'			\n'+
'		}\n'+
'		\n'+
'		var timestr = this.ref.module.getTime(offset_time,time_total);\n'+
'	\n'+
'		playerTime2.innerHTML = timestr;\n'+
'	}\n'+
'\n'+
'	playerHandle2.onDragEnd = function(x,y) {\n'+
'\n'+
'		x = x-hp.x;\n'+
'		\n'+
'		try {\n'+
'			var progressBarWidth = parseInt(playerProgressBar.offsetWidth);\n'+
'			var handleWidth = parseInt(playerHandle2.offsetWidth);\n'+
'			var time_total = this.ref.module.__parent.player.handler.getTotalSeconds();	\n'+
'			var offset_time = Math.ceil((x/(progressBarWidth-handleWidth))*time_total);\n'+
'			this.ref.module.__parent.player.handler.seek(offset_time);\n'+
'			\n'+
'			\n'+
'			this.ref.module.__parent.player.handler.setPlaystate(1);\n'+
'		}\n'+
'		catch(e){\n'+
'			//alert("err:"+e);\n'+
'			// No need to catch any exceptions..\n'+
'		}\n'+
'		\n'+
'		this.ref.isDragging = false;\n'+
'		\n'+
'	}\n'+
'\n'+
'\n'+
'}\n'+
'\n'+
'\n'+
'// Buffering\n'+
'\n'+
'var c = document.getElementById(this.module.config.playerBufferTextId);\n'+
'    \n'+
'\n'+
'this.buffering = function(pct) {\n'+
'    var text = "&nbsp;";\n'+
'    if (pct < 100) {\n'+
'        text = "Buffrar.. ";\n'+
'        if (pct > 0)\n'+
'            text += pct+"%";\n'+
'    }\n'+
'    if (c != null)\n'+
'	    c.innerHTML = text;\n'+
'\n'+
'}\n'+
'';
layouts.modBanner = {};
layouts.modBanner['modBanner.lo'] = '\n'+
'// in case current media is a playlist\n'+
'if (this.module.playlist != null) {\n'+
'    if (typeof showBanner == "function")\n'+
'        showBanner(this.module.playlist.name, this.module.clip);\n'+
'        \n'+
'}\n'+
'';
layouts.modTabList = {};
layouts.modTabList['modTabList.lo'] = 'var folders = Toolbox.array.clone(this.module.folders);\n'+
'\n'+
'var out = "";\n'+
'out += this.runTemplate("header");\n'+
'\n'+
'for (var i=0;i<folders.length;i++) {\n'+
'	//for (var i=0;i<3;i++) {\n'+
'	\n'+
'	this.i = i;\n'+
'	this.data = folders[i];\n'+
'	this.title = folders[i].title;\n'+
'	\n'+
'	if (this.i == this.selected) {\n'+
'		out += this.runTemplate("folderItemActive");\n'+
'	}\n'+
'	else {\n'+
'		out += this.runTemplate("folderItem");\n'+
'	}\n'+
'	\n'+
'}\n'+
'\n'+
'out += this.runTemplate("footer");\n'+
'this.output(out, this.module.config.tabListContainer);\n'+
'';
layouts.modTab_tipFriend = {};
layouts.modTab_tipFriend['modTab_tipFriend.lo'] = 'var out="";\n'+
'\n'+
'out+= this.runTemplate("content");\n'+
'\n'+
'out+= this.runTemplate("cover");\n'+
'\n'+
'\n'+
'this.setContent = function() {\n'+
'	\n'+
'	var title = "";\n'+
'	var thumb = "";\n'+
'	\n'+
'	\n'+
'	this.mediaInfo = this.module.mediaInfo;\n'+
'\n'+
'	if (this.mediaInfo != undefined && this.mediaInfo.thumbnails != undefined) {\n'+
'	\n'+
'		// set thumb\n'+
'    	if (this.module.__parent.config.CORE.devmode) {\n'+
'       	 var imgsrc = "thumb.php?"+this.mediaInfo.thumbnails[0].item;\n'+
'    	} else {\n'+
'       	 var imgsrc = "/"+this.mediaInfo.thumbnails[0].item.split("/").splice(1,99).join("/");;\n'+
'    	}\n'+
'    	thumb = \'<img src="\'+imgsrc+\'" width="96" height="72">\';\n'+
'    	\n'+
'    	// set title\n'+
'    	title = this.mediaInfo.title.truncate(25);\n'+
'	}\n'+
'\n'+
'	document.getElementById(\'tipFriendThumb\').innerHTML = thumb;\n'+
'	document.getElementById(\'tipFriendTitle\').innerHTML = title;\n'+
'}\n'+
'\n'+
'this.showLoading = function(cond,template,message) {\n'+
'	\n'+
'	var cover = document.getElementById(\'tipFriendCover\');\n'+
'	var content = document.getElementById(\'tipFriendContent\');\n'+
'	var coverText = document.getElementById(\'tipFriendCoverText\');\n'+
'	\n'+
'	\n'+
'	if (cond) {\n'+
'		this.message = message;\n'+
'		\n'+
'		this.output(this.runTemplate(template),\'tipFriendCoverText\');\n'+
'		\n'+
'		var coverMessage = document.getElementById(\'tipFriendCoverMessage\');\n'+
'		\n'+
'		cover.style.visibility = \'visible\';\n'+
'		coverText.style.visibility = \'visible\';\n'+
'		cover.style.width = content.offsetWidth+"px";\n'+
'		cover.style.height = content.offsetHeight+"px";\n'+
'		cover.style.top = content.offsetTop+"px";\n'+
'		cover.style.left = content.offsetLeft+"px";\n'+
'		\n'+
'		coverText.style.left =	(cover.offsetLeft+(cover.offsetWidth/2)-(coverText.offsetWidth/2))+"px";\n'+
'		coverText.style.top = 	(cover.offsetTop+(cover.offsetHeight/2)-(coverText.offsetHeight/2))+"px";\n'+
'		\n'+
'	}\n'+
'	else {\n'+
'		\n'+
'		cover.style.visibility = \'hidden\';\n'+
'		coverText.style.visibility = \'hidden\';\n'+
'		\n'+
'	}\n'+
'	\n'+
'}\n'+
'\n'+
'this.clearFields = function() {\n'+
'	\n'+
'	var tip_to_email	= document.getElementById(\'tipfriend_to_mail\');\n'+
'	var tip_from_email	= document.getElementById(\'tipfriend_from_mail\');\n'+
'	var tip_from_name	= document.getElementById(\'tipfriend_from_name\');\n'+
'	\n'+
'	var tip_to_email_container = document.getElementById(\'tipfriend_to_mail_container\');\n'+
'	var tip_from_email_container = document.getElementById(\'tipfriend_from_mail_container\');\n'+
'	var tip_from_name_container = document.getElementById(\'tipfriend_from_name_container\');\n'+
'	\n'+
'	var tip_message = document.getElementById(\'tipfriend_message\');\n'+
'	\n'+
'	\n'+
'	tip_to_email.value 				= \'\';\n'+
'	tip_from_email.value 			= \'\';\n'+
'	tip_from_name.value 			= \'\';\n'+
'	\n'+
'	tip_to_email_container.value 	= \'\';\n'+
'	tip_from_email_container.value 	= \'\';\n'+
'	tip_from_name_container.value 	= \'\';\n'+
'	\n'+
'	tip_message.value 				= \'\';\n'+
'\n'+
'}\n'+
'\n'+
'this.validate = function() {\n'+
'	\n'+
'	var tip_to_email	= document.getElementById(\'tipfriend_to_mail\');\n'+
'	var tip_from_email	= document.getElementById(\'tipfriend_from_mail\');\n'+
'	var tip_from_name	= document.getElementById(\'tipfriend_from_name\');\n'+
'	\n'+
'	var tip_to_email_container = document.getElementById(\'tipfriend_to_mail_container\');\n'+
'	var tip_from_email_container = document.getElementById(\'tipfriend_from_mail_container\');\n'+
'	var tip_from_name_container = document.getElementById(\'tipfriend_from_name_container\');\n'+
'	\n'+
'	var okToSend = true;\n'+
'	var errMsg = "";\n'+
'	var missingfields = [];\n'+
'	\n'+
'	if (Toolbox.string.isEmail(tip_to_email.value)) {\n'+
'		tip_to_email_container.style.border = "";\n'+
'	}\n'+
'	else {\n'+
'		okToSend = false;\n'+
'		missingfields[missingfields.length] = "mottagarens e-mail";\n'+
'				\n'+
'	}\n'+
'	\n'+
'	if (Toolbox.string.isEmail(tip_from_email.value)) {\n'+
'		\n'+
'		tip_from_email_container.style.border = "";\n'+
'	}\n'+
'	else {\n'+
'		okToSend = false;\n'+
'		missingfields[missingfields.length] = "din e-mail";\n'+
'	}\n'+
'	\n'+
'	if (tip_from_name.value.length >= 3) {\n'+
'		tip_from_name_container.style.border = "";\n'+
'		\n'+
'	}\n'+
'	else {\n'+
'		\n'+
'		okToSend = false;\n'+
'		missingfields[missingfields.length] = "ditt namn";\n'+
'		\n'+
'	}\n'+
'	\n'+
'	\n'+
'	okToSend = false;		\n'+
'	\n'+
'	\n'+
'	if (missingfields.length>0 && !okToSend) {\n'+
'	\n'+
'		return {error:\'Alla f&auml;lt utom "Meddelande" &auml;r obligatoriska. F&ouml;ljande f&auml;lt saknas eller &auml;r ej korrekt ifyllda: <b>\'+missingfields.join(\', \')+\'</b>\'};\n'+
'	\n'+
'	\n'+
'	}\n'+
'	\n'+
'	return okToSend;\n'+
'	\n'+
'}\n'+
'\n'+
'\n'+
'this.output(out,\'div_content_\'+this.module.moduleName);\n'+
'\n'+
'\n'+
'\n'+
'this.showLoading(false);\n'+
'\n'+
'\n'+
'\n'+
'\n'+
'\n'+
'\n'+
'';
layouts.modTab_contribute = {};
layouts.modTab_contribute['modTab_contribute.lo'] = 'var steps = [\'1\',\'2\',\'3\',\'4\'];\n'+
'\n'+
'this.step = function(step) {\n'+
'\n'+
'	var prefix = "contributeStep";\n'+
'	\n'+
'	\n'+
'	for (var i=0;i<steps.length;i++) {\n'+
'		\n'+
'		var mode = ( (i == step) ? \'inline\' : \'none\' );\n'+
'		\n'+
'		\n'+
'		document.getElementById(prefix+steps[i]).style.display = mode;\n'+
'	}\n'+
'\n'+
'}\n'+
'\n'+
'\n'+
'var out="";\n'+
'	\n'+
'out+=this.runTemplate("steps");\n'+
'		\n'+
'this.output(out,\'div_content_\'+this.module.moduleName);\n'+
'\n'+
'out="";\n'+
'\n'+
'\n'+
'this.writeData = function() {\n'+
'	\n'+
'	this.cssRegular		=	\'cursor:pointer;text-align:center;padding:3px;0px;3px;0px;font-size:14px;margin-bottom:1px\';\n'+
'	\n'+
'	this.cssActive		=	\'background-color:#bfd5f8;color:black\';\n'+
'	this.cssInActive	=	\'background-color:#e1e9fc;color:#9da3b1\';\n'+
'\n'+
'	for (var i=0;i<steps.length;i++) {\n'+
'		\n'+
'		this.tmpstep = i;\n'+
'		\n'+
'		var o = this.runTemplate("stepNav");\n'+
'	\n'+
'		this.output(o,\'contributeNav\'+(i+2));\n'+
'		\n'+
'	}\n'+
'	\n'+
'\n'+
'}\n'+
'\n'+
'\n'+
'this.validate = function(_id){\n'+
'\n'+
'	// Form fields.\n'+
'	var fields = [];\n'+
'	\n'+
'	fields[fields.length] = { name:\'Rubrik\',		obligatory:false,	type:\'textregular\',	data:$(\'contribute_head\'), text:$(\'contribute_head_text\') };\n'+
'//	fields[fields.length] = { name:\'Beskrivning\',	obligatory:false,	type:\'textfield\',	data:$(\'contribute_desc\'), text:$(\'contribute_desc_text\') };\n'+
'	\n'+
'	fields[fields.length] = { name:\'F&ouml;rnamn\',	obligatory:true,	type:\'textregular\',	data:$(\'contribute_firstname\'), text:$(\'contribute_lastname_text\') };\n'+
'	fields[fields.length] = { name:\'Efternamn\',		obligatory:true,	type:\'textregular\',	data:$(\'contribute_lastname\'), text:$(\'contribute_lastname_text\') };\n'+
'	fields[fields.length] = { name:\'E-post\',		obligatory:false,	type:\'mail\',		data:$(\'contribute_mail\'), text:$(\'contribute_mail_text\') };\n'+
'	fields[fields.length] = { name:\'Telefon\',		obligatory:false,	type:\'number\', 		data:$(\'contribute_tele\'), text:$(\'contribute_tele_text\') };\n'+
'	\n'+
'	fields[fields.length] = { name:\'Fil\',			type:\'file\', data:$(\'contribute_file\'), text:$(\'contribute_file_text\') };\n'+
'	\n'+
'	var errorFields = [];\n'+
'	\n'+
'	var ruleDesc = { textregular:\'Minst 2 tecken\',file:\'Otill&auml;ten filtyp\',textfield:\'Minst 10 tecken\',keywords:\'Minst ett s&ouml;kord\',number:\'Ska b&ouml;rja p&aring; 07\',mail:\'Ej korrekt ifylld\'}\n'+
'	\n'+
'	var errorArr = [];\n'+
'	\n'+
'	// Iterate through fields, evaluating each.\n'+
'	for (var i=0;i<fields.length;i++) {\n'+
'		\n'+
'		var field = fields[i];\n'+
'		\n'+
'		if (_id && field.data.id != _id)\n'+
'			continue;\n'+
'		\n'+
'		var ruleType = field.type;\n'+
'		var data = field.data.value;\n'+
'		\n'+
'		var failed = false;\n'+
'		\n'+
'		// Rule for regular text.\n'+
'		if (ruleType == \'textregular\') {\n'+
'			\n'+
'			if (field.data.value.length < 2)\n'+
'				failed = true;				\n'+
'		}\n'+
'		\n'+
'		// Rule for text fields.\n'+
'		if (ruleType == \'textfield\') {\n'+
'			\n'+
'			if (field.data.value.length < 10 )\n'+
'				failed = true;		\n'+
'		}\n'+
'		\n'+
'		// Rule for files.\n'+
'		if (ruleType == \'file\') {\n'+
'		\n'+
'			var ext = field.data.value.split(\'.\');\n'+
'			ext = ext[ext.length-1];\n'+
'	\n'+
'			if (ext != \'mpeg\' && ext !=  \'mpg\' && ext != \'mov\' && ext != \'avi\' && ext != \'wmv\' && ext != \'3gp\' && ext != \'mp4\')	\n'+
'				failed = true;\n'+
'		}\n'+
'		\n'+
'		// Rule for keywords.\n'+
'		if (ruleType == \'keywords\') {\n'+
'			\n'+
'			var keywords = field.data.value.split(\',\');\n'+
'\n'+
'			if (!keywords || keywords.length==0 || keywords[0].length == 0)\n'+
'				failed = true;\n'+
'				\n'+
'		}\n'+
'		\n'+
'		// Rule for email.\n'+
'		if (ruleType == \'mail\') {\n'+
'		\n'+
'			if ( !Toolbox.string.isEmail(field.data.value))\n'+
'				failed = true;\n'+
'				\n'+
'		}\n'+
'		\n'+
'		\n'+
'		// Rule for number.\n'+
'		if (ruleType == \'number\') {\n'+
'\n'+
'			if (field.data.value.substring(0,2) == \'07\') {\n'+
'				var ns = field.data.value.substring(1,field.data.value.length);\n'+
'				ns = \'46\'+ns;\n'+
'				field.data.value = ns;\n'+
'			}\n'+
'			\n'+
'			if (isNaN(parseInt(field.data.value)))\n'+
'				failed = true;\n'+
'				\n'+
'			if ( field.data.value.substring(0,3) != \'467\' )\n'+
'				failed = true;\n'+
'				\n'+
'		}\n'+
'		\n'+
'		if (field.data.value == \'\' && field.obligatory == false)\n'+
'			failed = false;		\n'+
'	\n'+
'		if (failed) {\n'+
'		\n'+
'			field.text.innerHTML = \'<span style="font-size:10px;color:red;background-color:white;padding:3px;">(\'+ruleDesc[ruleType]+\')</span>\';\n'+
'			//field.data.style.backgroundColor = \'gray\';\n'+
'			//errorFields[errorFields.length] = {message:field.name + "("+ruleDesc[ruleType]+")",data:field.data,text:field.text};\n'+
'			errorArr[errorArr.length] = field.name /*+ ": "+ruleDesc[ruleType]*/;\n'+
'		\n'+
'		}\n'+
'		else {\n'+
'		\n'+
'			\n'+
'			\n'+
'			field.text.innerHTML = \'\';\n'+
'			field.data.style.backgroundColor = \'\';\n'+
'		\n'+
'		}\n'+
'	\n'+
'	}\n'+
'	\n'+
'	var errorMsg = "F&ouml;ljande f&auml;lt &auml;r ej korrekt ifyllda:<br>"+ errorArr.join(\', \');\n'+
'	\n'+
'	if (_id)\n'+
'		return;\n'+
'	\n'+
'	// Dispatch error message if errorArr > 0.\n'+
'	if (errorArr.length>0) {\n'+
'		\n'+
'		sendObj = {visible:true,template:\'coverMessageDialogueOk\',head:\'Felmeddelande\',message:errorMsg,module:this.module.moduleName};\n'+
'	\n'+
'		this.module.__parent.modHandler.updateEvent( [ {name:\'tab_notice\',value:sendObj} ],true );\n'+
'	\n'+
'	\n'+
'	}\n'+
'	else {\n'+
'	\n'+
'		// All ok. Post data.\n'+
'		$(\'contribute_form\').target = \'modTab_contribute_iframe\';\n'+
'		\n'+
'		\n'+
'		var loc = document.location.href.split(\'?\')\n'+
'		\n'+
'		var absPath = loc[0].split(\'/\');\n'+
'		absPath.splice(absPath.length-1,absPath.length);\n'+
'		absPath = absPath.join(\'/\')+\'/\'+this.module.config.callbackURL;\n'+
'		\n'+
'		$(\'contribute_callback\').value = absPath;\n'+
'		\n'+
'		$(\'contribute_form\').action = this.module.config.backendURL;\n'+
'		$(\'contribute_form\').submit();\n'+
'		\n'+
'		sendObj = {visible:true,template:\'coverMessageNotice\',head:\'Meddelande\',message:\'Ett &ouml;gonblick, laddar upp din film.<br>Detta kan ta flera minuter, beroende p&auml; filmens storlek.\',module:this.module.moduleName};\n'+
'	\n'+
'		this.module.__parent.modHandler.updateEvent( [ {name:\'tab_notice\',value:sendObj} ],true );\n'+
'		\n'+
'	}\n'+
'	\n'+
'\n'+
'}\n'+
'\n'+
'\n'+
'	\n'+
'\n'+
'this.sendTerms = function() {\n'+
'\n'+
'	sendObj = {\n'+
'		visible:true,\n'+
'		template:\'coverTerms\',\n'+
'		head:\'Anv&auml;ndarvillkor\',\n'+
'		message:\'GL&Ouml;M INTE: Skriv vad filmen inneh&aring;ller, vem du &auml;r, hur vi kan kontakta dig, samt om du vill vara anonym.<br>Vill du vara anonym &auml;r redaktionen, under straffansvar, skyldig att h&aring;lla din identitet hemlig f&ouml;r utomst&aring;ende. Du skyddas av meddelandeskyddet i tryckfrihetsf&ouml;rordningen, som &auml;r en grundlag.<br><br>Du som skickar in filmen ansvarar f&ouml;r att det &auml;r du som har filmat den eller att du f&aring;tt tillst&aring;nd fr&aring;n upphovsmannen att publicera den p&aring; GP.tv enligt anv&auml;ndarvillkoren. Om det visas personer p&aring; filmen som g&aring;r att k&auml;nna igen, t&auml;nk p&aring; att f&aring; godk&auml;nnande fr&aring;n dem innan du laddar upp filmen.<br>GP kommer att polisanm&auml;la f&ouml;rs&ouml;k att publicera upphovsr&auml;ttsskyddat material p&aring; GP.tv.<br><br>Publicerade filmer av h&ouml;gt nyhetsv&auml;rde ers&auml;tts med 500 kronor, &ouml;vriga publicerade filmer &auml;r med i en t&auml;vling om en Ipod Shuffle. Med filmer av h&ouml;gt nyhetsv&auml;rde avser vi s&aring;dana som f&ouml;rest&auml;ller en dramatisk h&auml;ndelse som inte varit k&auml;nd f&ouml;r oss sen tidigare.<br><br>T&auml;NK P&aring; DET H&auml;R:<br>- Var noga med att skriva om du vill vara anonym.<br>- Respektera enskilda m&auml;nniskors privatliv.<br>- G&aring; inte f&ouml;r n&auml;ra olyckor. Stanna utanf&ouml;r avsp&auml;rrningarna.<br>- Om personers ansikten syns tydligt p&aring; filmen, fr&aring;ga dem om lov f&ouml;rst. <br><br>Vi bed&ouml;mer alla inkomna filmer och g&aring;r sj&auml;lva vidare (g&ouml;r egna inslag) med dem som vi anser som intressanta f&ouml;r v&aring;ra l&auml;sare.<br>GP f&ouml;rbeh&aring;ller sig r&auml;tten att kostnadsfritt publicera, arkivera och &aring;teranv&auml;nda ins&auml;nt material i alla tidningens publiceringsformer, s&aring;v&auml;l den tryckta papperstidningen, som webb, mobil och andra kanaler, liksom i n&auml;tverket mktv, d&auml;r ____ ing&aring;r.\',\n'+
'		module:this.module.moduleName};\n'+
'	\n'+
'	this.module.__parent.modHandler.updateEvent( [ {name:\'tab_notice\',value:sendObj} ],true );\n'+
'\n'+
'}	\n'+
'\n'+
'\n'+
'this.arrowURL = \'<img src="\'+this.getURL(\'arrow.gif\')+\'">\';\n'+
'\n'+
'out+=this.runTemplate("step1");\n'+
'	\n'+
'out+=this.runTemplate("step2");\n'+
'	\n'+
'out+=this.runTemplate("step3");\n'+
'\n'+
'out+=this.runTemplate("step4");\n'+
'\n'+
'this.output(out,"contributeContent");\n'+
'\n'+
'\n'+
'\n'+
'this.step(0);\n'+
'\n'+
'this.writeData();';
layouts.modMediaList = {};
layouts.modMediaList['modMediaList.lo'] = 'var out = "";\n'+
'\n'+
'// The index of the current playing file.\n'+
'this.module.currFileRunning = -1;\n'+
'\n'+
'this.currPos = 0;\n'+
'\n'+
'\n'+
'// load the container start template\n'+
'\n'+
'\n'+
'\n'+
'this.getDate = function(s) {\n'+
'	// cast to string\n'+
'	s+="";\n'+
'\n'+
'	k = s.substring(0,4)+"-"+s.substring(4,6)+"-"+s.substring(6,8);\n'+
'	return	k;\n'+
'	\n'+
'}\n'+
'\n'+
'\n'+
'var thumbArray = [];\n'+
'\n'+
'this.getThumb = function(file,pos) {\n'+
'    \n'+
'    var divcontent = "";\n'+
'    \n'+
'    var divstart = \'<div style="width:93px;height:70px;float:left;">\';\n'+
'    var divend = \'</div>\';\n'+
'    var imgsrc=\'\';\n'+
'    \n'+
'    if (file.thumbnails && file.thumbnails[0].item) {\n'+
'        if (this.module.__parent.config.CORE.devmode) {\n'+
'            imgsrc = "thumb.php?"+file.thumbnails[0].item;\n'+
'        } else {\n'+
'	        imgsrc = "/"+file.thumbnails[0].item.split("/").splice(1,99).join("/");\n'+
'	    }\n'+
'	    \n'+
'	    var src2 = imgsrc;\n'+
'		divcontent = \'<img id="mediaimg_\'+pos+\'" style="margin:0px;padding:0px;" width="93" height="70" src="\'+src2+\'">\'\n'+
'\n'+
'    }\n'+
'\n'+
'    \n'+
'    thumbArray[thumbArray.length] = {div:\'media_\'+pos,img:\'mediaimg_\'+pos,imgsrc:imgsrc,p:pos};\n'+
'\n'+
'	return divstart+divcontent+divend;\n'+
'}\n'+
'\n'+
'var defImg=\'<div style="width:93px;height:70px;float:left;">Ingen bild</div>\';\n'+
'\n'+
'\n'+
'\n'+
'this.render = function(start,stop,active) {\n'+
'	\n'+
'	var listout="";\n'+
'	\n'+
'	// Put loading here..\n'+
'\n'+
'	start = start ? start : 0;\n'+
'	if (this.module.folderItem.file != null) {\n'+
'		stop = stop ? stop : this.module.folderItem.file.length;\n'+
'\n'+
'		if (stop>this.module.folderItem.file.length)\n'+
'			stop = this.module.folderItem.file.length;\n'+
'	} else {\n'+
'		stop = 0;\n'+
'	}\n'+
'\n'+
'	var selected;\n'+
'	\n'+
'	if (this.module.currFileRunning)\n'+
'		selected = this.module.currFileRunning;\n'+
'\n'+
'	displayDivs = []; \n'+
'	\n'+
'	renderDivs = false;\n'+
'	\n'+
'	for ( start  ; start < stop ;start++) {\n'+
'		\n'+
'		this.currPos = start;\n'+
'		this.len = stop;\n'+
'		\n'+
'		this.data = this.module.folderItem.file[this.currPos];\n'+
'		\n'+
'		this.image = this.getThumb(this.data,this.currPos,true);\n'+
'	\n'+
'		if (this.data.pubfrom > 0)\n'+
'			this.date = this.getDate(this.data.pubfrom);\n'+
'		else\n'+
'			this.date = this.getDate(this.data.published);\n'+
'\n'+
'		if (active == undefined)\n'+
'			this.css=\'display:none\';\n'+
'		else\n'+
'			this.css=\'\';\n'+
'	\n'+
'		if (this.data.id == this.module.currFileHash) {\n'+
'			this.datecolor = \'#888689\';\n'+
'			var nextOut = this.runTemplate("activeFile");\n'+
'			\n'+
'		}\n'+
'		else {\n'+
'			this.datecolor="#888689";\n'+
'			var nextOut = this.runTemplate("normalFile");\n'+
'			\n'+
'		}\n'+
'		\n'+
'		//this.background = ((this.currPos%2)==0) ? "#FFFFFF" : "#FFFFFF";\n'+
'	\n'+
'		listout += nextOut;\n'+
'		\n'+
'		if (active == undefined)\n'+
'			displayDivs[displayDivs.length] = \'media_\'+this.currPos;\n'+
'		\n'+
'		this.image = "";\n'+
'	}\n'+
'\n'+
'	\n'+
'	// Fix.\n'+
'	var pageContainer = document.getElementById(\'dragContent\');\n'+
'	\n'+
'	this.output(listout,pageContainer.id);\n'+
'\n'+
'\n'+
'	for (var i = 0;i<displayDivs.length;i++) {\n'+
'		var div = document.getElementById(displayDivs[i]);\n'+
'		Element.hide(div);\n'+
'	}\n'+
'	\n'+
'}\n'+
'\n'+
'var displayDivs = [];\n'+
'var hideDivs = [];\n'+
'var renderDivs = false;\n'+
'\n'+
'var out="";\n'+
'out+= this.runTemplate("containerStart");\n'+
'out+= this.runTemplate("containerEnd");\n'+
'this.output(out, this.module.config.playerMediaId);\n'+
'\n'+
'this.prevTemplate = null;\n'+
'this.prevTemplateData = null;\n'+
'this.prevItem = null;\n'+
'\n'+
'this.pos = 0;\n'+
'\n'+
'this.replaceTemplate = function(pos) {\n'+
'\n'+
'	this.render(start,stop,pos);\n'+
'	\n'+
'	return;\n'+
'	\n'+
'}\n'+
'\n'+
'this.sendHoverEvent = function(div,idx,pos) {\n'+
'	var hoverData = this.module.folderItem.file[idx].desc;\n'+
'	this.module.__parent.modHandler.updateEvent([{name:\'new_menuitem_hover\',value:{div:div,data:hoverData,pos:pos}}]);\n'+
'\n'+
'}\n'+
'\n'+
'this.sendHoverOutEvent = function() {\n'+
'\n'+
'	this.module.__parent.modHandler.updateEvent([{name:\'new_menuitem_hover_out\',value:Math.random()}]);\n'+
'\n'+
'}\n'+
'\n'+
'\n'+
'this.runFile = function() {\n'+
'\n'+
'\n'+
'	this.module.__parent.player.setFile(this.thumb.url);\n'+
'\n'+
'}\n'+
'\n'+
'\n'+
'\n'+
'// Create references to the images\n'+
'\n'+
'\n'+
'// Init drag and drop for the scrollbar.\n'+
'/*\n'+
'var container = document.getElementById(\'dragContainer\');\n'+
'var content = document.getElementById(\'dragContent\');\n'+
'var count = document.getElementById(\'count\');\n'+
'*/\n'+
'\n'+
'var page = -1;\n'+
'var pages = 1;\n'+
'\n'+
'var start,stop;\n'+
'\n'+
'\n'+
'__tmpFunc2OLD =  function(containerid,contentid) {\n'+
'\n'+
'		var thisPageOffset = content.offsetTop;\n'+
'		\n'+
'		var scrollableArea = content.offsetHeight-container.offsetHeight;\n'+
'\n'+
'		var maxscroll = container.offsetHeight;\n'+
'\n'+
'		var requested = 0 - Math.round(content.offsetHeight * ((page-1) / pages) );\n'+
'		var requestedmax = 0 - Math.round(scrollableArea * (pages / pages) );\n'+
'		\n'+
'		if (requested < requestedmax && requestedmax < 0)\n'+
'			requested = requestedmax;\n'+
'		\n'+
'		var newPos = (requested - thisPageOffset);\n'+
'		newPos = thisPageOffset+ (newPos/10);\n'+
'\n'+
'		if (newPos == requested)\n'+
'			return;\n'+
'		\n'+
'		content.style.top = newPos+"px";\n'+
'		\n'+
'}\n'+
'\n'+
'// Show loading screen.\n'+
'this.setLoading = function() {\n'+
'	\n'+
'	var out = this.runTemplate(\'loading\');\n'+
'\n'+
'	this.output(out,\'dragContent\');\n'+
'	\n'+
'}\n'+
'\n'+
'this.go = function(dir) {\n'+
'	\n'+
'	var count = document.getElementById(\'count\');\n'+
'	\n'+
'	var clipsPerPage = 6;\n'+
'	\n'+
'	\n'+
'	// Store total file length\n'+
'	var totalFiles = 0;\n'+
'	if (this.module.folderItem.file != null)\n'+
'		var totalFiles = this.module.folderItem.file.length;\n'+
'		\n'+
'	\n'+
'	pages = Math.ceil(totalFiles/clipsPerPage);\n'+
'	\n'+
'	if ((totalFiles > 0) && ((page+dir)+1 > pages || (page+dir)+1 < 1))\n'+
'		return;\n'+
'	\n'+
'	var clipsPerPage = 6;\n'+
'\n'+
'	this.prevItem = null;\n'+
'	this.pos = null;\n'+
'	\n'+
'	page+=dir;\n'+
'	\n'+
'	start = page * clipsPerPage;\n'+
'	stop = start + clipsPerPage;\n'+
'	\n'+
'	\n'+
'	count.innerHTML = (page+1) + "/" + pages ;\n'+
'	\n'+
'	this.render(start,stop);\n'+
'	\n'+
'	\n'+
'	\n'+
'\n'+
'	\n'+
'\n'+
'}\n'+
'\n'+
'this.go2 = function(dir) {\n'+
'	\n'+
'	var scrollableArea = content.offsetHeight-container.offsetHeight;\n'+
'	var maxscroll = container.offsetHeight;\n'+
'	var current = content.offsetTop;\n'+
'	\n'+
'	// indicate which divs are to be displayed ...\n'+
'	\n'+
'	\n'+
'	pages= 1;\n'+
'\n'+
'	pages += Math.ceil((scrollableArea/maxscroll));\n'+
'	\n'+
'		\n'+
'	if ((page+dir) <=0 || (page+dir) > pages )\n'+
'		return; \n'+
'	\n'+
'	page+=dir;\n'+
'	\n'+
'	var requested = 0 - (content.offsetHeight * ((page-1) / pages) );\n'+
'	\n'+
'	var start,stop;\n'+
'	start = (requested ==0) ? 0 : (container.offsetTop-requested) ;\n'+
'	//start = (container.offsetTop-requested) ;\n'+
'\n'+
'	stop = ( (container.offsetTop+container.offsetHeight)-requested);\n'+
'	\n'+
'\n'+
'	for ( var i=0; i< thumbArray.length;i++) {\n'+
'\n'+
'		//var div = thumbArray[i].div;\n'+
'		var img = thumbArray[i].img;\n'+
'		var div = thumbArray[i].div;\n'+
'\n'+
'		var imgsrc = thumbArray[i].imgsrc;\n'+
'		\n'+
'		\n'+
'		if ( (div.offsetTop >= start || (div.offsetTop+div.offsetHeight) >= start ) && div.offsetTop < stop) {\n'+
'\n'+
'\n'+
'			if (img.src != imgsrc) {\n'+
'			\n'+
'				img.src = imgsrc;\n'+
'				\n'+
'			}\n'+
'		\n'+
'			\n'+
'		}\n'+
'\n'+
'		\n'+
'	}\n'+
'\n'+
'\n'+
'	\n'+
'	count.innerHTML = page + "/" + pages ;\n'+
'	\n'+
'}\n'+
'\n'+
'\n'+
'__getPos = function (current,requested,steps) {\n'+
'\n'+
'	return playingPos;\n'+
'}\n'+
'\n'+
'\n'+
'__tmpFunc2 = function() {\n'+
'\n'+
'	if (displayDivs.length>0) {\n'+
'		\n'+
'		var g = displayDivs.splice(0,1);\n'+
'		var g1Scope = "scope_"+(displayDivs.length%2);\n'+
'		\n'+
'		var g2 = displayDivs.splice(0,1);\n'+
'		var g2Scope = "scope_"+(displayDivs.length%2);\n'+
'	\n'+
'		\n'+
'		\n'+
'		var div1 = document.getElementById(g);\n'+
'		var div2 = document.getElementById(g2);\n'+
'		\n'+
'		if (div1) {\n'+
'			Element.hide(div1);\n'+
'			try {\n'+
'				Effect.Appear(div1.id,{duration:0.7,queue:{position:\'end\',scope:g1Scope} });\n'+
'			}\n'+
'			catch(e){\n'+
'				\n'+
'			}\n'+
'		\n'+
'		}\n'+
'		\n'+
'		if (div2) {\n'+
'			Element.hide(div2);\n'+
'			try {\n'+
'				Effect.Appear(div2.id,{duration:0.7,queue:{position:\'end\',scope:g2Scope} });\n'+
'				}\n'+
'			catch(e){\n'+
'				\n'+
'			}\n'+
'		\n'+
'		}\n'+
'		\n'+
'		\n'+
'	\n'+
'	}\n'+
'	\n'+
'\n'+
'\n'+
'}\n'+
'\n'+
'__tmpInterval = setInterval(\'__tmpFunc2()\',300);\n'+
'';
layouts.modBandwidthTest = {};
layouts.modTab_playing = {};
layouts.modTab_playing['modTab_playing.lo'] = '\n'+
'\n'+
'this.runClip = function(index) {\n'+
'	\n'+
'	this.module.setClip(index, -1);\n'+
'\n'+
'}\n'+
'\n'+
'this.writeData = function() {\n'+
'\n'+
'	var out = "";\n'+
'	\n'+
'	// Are there any files?\n'+
'	if (this.response && this.response.length > 0) {\n'+
'	\n'+
'		this.playlistData = this.module.playlistData;\n'+
'	\n'+
'		for (var i=0;i<this.response.length;i++) {\n'+
'			\n'+
'				\n'+
'			this.data = this.response[i];\n'+
'			if(this.data.thumbnails != null) {\n'+
'			\n'+
'				var playlistHost = this.playlistData.path.split("/")[0];\n'+
'				var thumbHost = this.data.thumbnails[0].item.split("/")[0];\n'+
'				\n'+
'				if (this.module.__parent.config.CORE.devmode) {\n'+
'					this.thumb = "thumb.php?"+this.data.thumbnails[0].item;\n'+
'				} else {\n'+
'					if (playlistHost != thumbHost) {\n'+
'						this.thumb = "http://"+this.data.thumbnails[0].item;\n'+
'					} else {\n'+
'						this.thumb = "/"+this.data.thumbnails[0].item.split("/").splice(1,99).join("/");\n'+
'					}\n'+
'				}\n'+
'			} else {\n'+
'				this.thumb = this.getURL(\'no_thumb.gif\');\n'+
'			}\n'+
'			\n'+
'			this.i = i;\n'+
'			if (this.module.playlistIndex != i)\n'+
'				out += this.runTemplate("inactiveClip");\n'+
'			else\n'+
'				out += this.runTemplate("activeClip");\n'+
'							\n'+
'		}\n'+
'		\n'+
'		out+=this.runTemplate("clipText");\n'+
'	\n'+
'	}\n'+
'	else {\n'+
'		out+=out+=this.runTemplate("noClipRunning");\n'+
'	}\n'+
'\n'+
'	if ((this.playlistData == null) && (this.mediaData != null)) {\n'+
'\n'+
'		out = this.runTemplate("mediaText");\n'+
'\n'+
'	}\n'+
'\n'+
'	if (out != "")\n'+
'		this.output(out,\'div_content_\'+this.module.moduleName);\n'+
'	\n'+
'}\n'+
'this.sendHoverEvent = function(div,idx,pos) {\n'+
'    \n'+
'    var hoverData = this.response[idx].desc;\n'+
'    this.module.__parent.modHandler.updateEvent([{name:\'new_menuitem_hover\',value:{div:div,data:hoverData,pos:pos}}]);\n'+
'\n'+
'}\n'+
'\n'+
'this.sendHoverOutEvent = function() {\n'+
'\n'+
'	this.module.__parent.modHandler.updateEvent([{name:\'new_menuitem_hover_out\',value:Math.random()}]);\n'+
'\n'+
'}\n'+
'\n'+
'\n'+
'';
layouts.modTabs = {};
layouts.modTabs['modTabs.lo'] = '\n'+
'\n'+
'\n'+
'this.writeTabs = function() {\n'+
'\n'+
'	var out="";\n'+
'	\n'+
'	var i = 0;\n'+
'	var prev = null;\n'+
'	\n'+
'	out="";\n'+
'	out+= this.runTemplate("flikWrapperStart");\n'+
'	out+= this.runTemplate("separator");\n'+
'	\n'+
'	var tabList = this.module.tabList;\n'+
'	\n'+
'	for (mod in tabList) {\n'+
'	\n'+
'		this.title = tabList[mod];\n'+
'		this.id = mod;\n'+
'		// load the container end template\n'+
'		if (this.module.selectedTab == mod) {\n'+
'			out+= this.runTemplate("flikActive");\n'+
'			out+= this.runTemplate("separatorActive");\n'+
'		}\n'+
'		else {\n'+
'			out+= this.runTemplate("flik");\n'+
'			out+= this.runTemplate("separator");\n'+
'		}\n'+
'	\n'+
'		//if (i != Toolbox.object.getObjSize(tabList)-1)\n'+
'\n'+
'		i++;\n'+
'	}\n'+
'	out+= this.runTemplate("separatorEnd");\n'+
'	out+= this.runTemplate("flikWrapperEnd");\n'+
'\n'+
'this.output(out,this.module.config.tabContainerId);\n'+
'\n'+
'}\n'+
'\n'+
'this.setNotice = function(obj) {\n'+
'	\n'+
'	\n'+
'	// Input data\n'+
'	var cond = obj.visible;\n'+
'	var template = obj.template;\n'+
'	var noticeMessage = obj.message;\n'+
'	var noticeHead = obj.head;\n'+
'	var moduleName = obj.module;\n'+
'	\n'+
'	// Output objects\n'+
'\n'+
'	var cover 				= document.getElementById(\'div_message_cover_\'+moduleName);\n'+
'	var content 			= document.getElementById(\'div_container_\'+moduleName);\n'+
'	var messageText 		= document.getElementById(\'div_message_text_\'+moduleName);\n'+
'	var messageTextWrapper 	= document.getElementById(\'div_message_text_wrapper_\'+moduleName);\n'+
'	var messageContainer 	= document.getElementById(\'div_message_container_\'+moduleName);\n'+
'	var messageHead			= document.getElementById(\'div_message_head_\'+moduleName);\n'+
'	\n'+
'	if (cond) {\n'+
'		\n'+
'		messageContainer.style.display=\'inline\';\n'+
'		\n'+
'		this.noticeMessage = noticeMessage;\n'+
'		this.noticeHead = noticeHead;\n'+
'		this.moduleName = moduleName;\n'+
'		\n'+
'		\n'+
'		this.output(this.runTemplate(template),messageText.id);\n'+
'		\n'+
'		// Tmp\n'+
'		messageHead.innerHTML = this.noticeHead;\n'+
'		\n'+
'		cover.style.width = content.offsetWidth+"px";//content.offsetWidth+"px";\n'+
'		cover.style.height = content.offsetHeight+"px";//content.offsetHeight+"px";\n'+
'		cover.style.left = \'0px\';\n'+
'		cover.style.top = \'0px\';\n'+
'		\n'+
'		messageTextWrapper.style.left = ( (content.offsetWidth-messageTextWrapper.offsetWidth)/2 ) + "px";\n'+
'		messageTextWrapper.style.top = ( (content.offsetHeight-messageTextWrapper.offsetHeight)/2 ) + "px";\n'+
'		\n'+
'		\n'+
'		messageText.style.visibility=\'visible\';\n'+
'		messageContainer.style.visibility = \'visible\';\n'+
'		\n'+
'	}\n'+
'	else {\n'+
'		messageContainer.style.display = \'none\';\n'+
'		messageText.style.visibility=\'hidden\';\n'+
'		messageContainer.style.visibility = \'hidden\';\n'+
'		\n'+
'	}\n'+
'	\n'+
'}\n'+
'\n'+
'\n'+
'this.createTabContent = function() {\n'+
'\n'+
'	var out_tab = "";\n'+
'\n'+
'	for (var i=0;i<this.module.tabModules.length;i++) {\n'+
'		\n'+
'		var moduleName = this.module.tabModules[i];\n'+
'		\n'+
'		this.divContainerId 			= \'div_container_\'+moduleName;\n'+
'		this.divContentId 				= \'div_content_\'+moduleName;\n'+
'		\n'+
'		this.divMessageContainerId 		= \'div_message_container_\'+moduleName;\n'+
'		this.divMessageTextId			= \'div_message_text_\'+moduleName;		\n'+
'		this.divMessageHeadId			= \'div_message_head_\'+moduleName;	\n'+
'		this.divMessageCoverId			= \'div_message_cover_\'+moduleName;\n'+
'		this.divMessageTextWrapperId 	= \'div_message_text_wrapper_\'+moduleName;\n'+
'		\n'+
'		var data = this.runTemplate(\'tabPlaceHolder\');\n'+
'\n'+
'		out_tab += data;\n'+
'\n'+
'		\n'+
'	}\n'+
'	\n'+
'	this.output(out_tab,this.module.config.tabContentId);\n'+
'	\n'+
'}\n'+
'\n'+
'\n'+
'\n'+
'';
/**
* Module for managing live streams
*
* @author Absoft AB
* @version 1.01
* @copyright Absoft AB, 24 January, 2007
* @package default
**/
var modLiveStream = function(parent) {
this.__parent = parent;
this.moduleName = null;
this.streamData = null;
this.init = function() {
Debug.warning("modLive","init","started.");
this.__parent.modHandler.module(this.moduleName).subscribe(0,['unknown_file_type']);
this.lm = new Layout.manager(this);
}
this.eventReceiver = function(data) {
if (data["unknown_file_type"]) {
var fileExt = Toolbox.getFileExt(data["unknown_file_type"].URL);
if (fileExt != "fsx") return;
this.loadStream(data["unknown_file_type"].URL);
}
}
this.loadStream = function(file) {
if (this.__parent.config.CORE.devmode)
var url = "xml.php?"+file;
else {
file = file.replace("http://","");
var url = "/"+file.split("/").splice(1,99).join("/");
url = url.replace("//","/");
}
this.__parent.ajax.externalCall(this,'XML', url,'','cbLoadStream');
}
this.cbLoadStream = function(response,txt) {
var data;
data = Struct.render(response);
try {
var url = data.FSX[0].ENTRY[0].REF[0].HREF;
}
catch(e){}
if (url != null) {
this.runStream(url);
}
}
this.runStream = function(file) {
this.__parent.modHandler.updateEvent([{name:'controls_show_seekbar',value:false}]);
this.__parent.player.setFile(file);
this.lm.init();
}
}
/**
* Module for playback controls
*
* @author Absoft AB
* @version 1.00
* @copyright Absoft AB, 24 January, 2007
* @package default
**/
var modControls = function(parent) {
this.__parent = parent;
this.moduleName = null;
this.lm = null;
this.mediaInfo = null;
this.timeMode = 1;
this.init = function() {
this.__parent.modHandler.module(this.moduleName).subscribe(0,['time_played','time_total','media_buffering','media_new_playstate','controls_show_seekbar','new_window_state','new_clicktoplay','new_volume','media_info']);
if (this.config.timeMode != null)
this.timeMode = this.config.timeMode;
this.lm = new Layout.manager(this);
this.lm.init();
}
var time_played;
var time_total;
var media_ended;
this.eventReceiver = function(data) {
if (data['media_new_playstate']) {
try {
this.lm.setState(data['media_new_playstate']);
}
catch (e) {
}
}
if (data['controls_show_seekbar'] != undefined) {
try {
this.lm.showSeekbar( ((data['controls_show_seekbar']) ? 'visible' : 'hidden') );
}
catch (e) {
}
}
if (data['new_volume']) {
alert("new volume:"+data['new_volume'])
}
if (data['media_buffering']) {
var buffer = parseInt(data['media_buffering']);
if (buffer >= 100 && !isNaN(buffer)) {
try {
this.__parent.player.handler.setPlaystate(1);
}
catch (e){}
}
if (buffer < 100 && !isNaN(buffer)) {
try {
this.__parent.player.handler.setPlaystate(0);
}
catch (e){}
}
this.lm.buffering(data['media_buffering']);
}
if (data['media_info']) {
this.mediaInfo = data['media_info'];
}
if (data['time_played'] != null) {
time_played = data['time_played'];
}
if (data['time_total'] != null) {
time_total = data['time_total'];
}
if (media_ended == true)
alert('media ended..(controls)');
if (this.lm && this.lm.updateSeekhandle) {
try {
this.lm.updateSeekhandle(time_played,time_total);
}
catch (e) {
}
}
if (data["new_clicktoplay"]) {
try {
this.lm.setState(0);
}catch(e){}
}
}
this.skip = function(step) {
this.__parent.modHandler.updateEvent([{name:'skip',value:step}],true);
}
this.nextTimeMode = function() {
if (this.config.showTotal == true)
var limit = 1;
else
var limit = 2;
if ((this.timeMode+1) >limit)
this.timeMode=0;
else
this.timeMode++;
}
this.getTimeMode = function(start,end) {
if (this.timeMode == 0)
return {prefix:"",time:start,total:end};
if (this.timeMode == 1)
return {prefix:"-",time:(end-start),total:end};
if (this.timeMode == 2)
return {prefix:"",time:end,total:0};
}
this.getTime = function(start,end) {
var _start,_end;
_start = start;
_end = end;
if (_end == null)
_end = 0;
var data = this.getTimeMode(_start,_end);
if (isNaN(data.time)) return "";
var res = data.prefix+Toolbox.convert.formatSecs(data.time);
if (data.total >= 0 && this.config.showTotal)
res += " / "+Toolbox.convert.formatSecs(data.total);
return res;
}
}
/**
* Module for showing banners connected to media played
*
* @author Absoft AB
* @version 1.00
* @copyright Absoft AB, 24 January, 2007
* @package default
**/
var modBanner = function(parent) {
this.__parent = parent;
this.moduleName = null;
this.init = function() {
Debug.warning("modBanner","init","started");
this.lm = new Layout.manager(this);
this.__parent.modHandler.module(this.moduleName).subscribe(0,['current_obj_data']);
}
this.eventReceiver = function(data) {
if (data["current_obj_data"]) {
this.playlist = data["current_obj_data"].playlist;
this.clip = data["current_obj_data"].clip;
this.file = data["current_obj_data"].file;
this.lm.init();
}
}
}
/**
* Module for presenting folders in a tab list
*
* @author Absoft AB
* @version 1.00
* @copyright Absoft AB, 24 January, 2007
* @package default
**/
var modTabList = function(parent) {
this.__parent = parent;
this.moduleName = null;
this.init = function() {
Debug.warning("modFolderList","init","started");
this.startPath=this.__parent.config.modTabList.startPath;
if (this.__parent.config.GET.path != null)
this.activePath = this.__parent.config.GET.path;
this.lm = new Layout.manager(this);
this.readFolder(this.startPath);
}
this.eventReceiver = function(data) {
}
this.readFolder = function(path) {
Debug.warning("modFolderList","readFolder","requesting backend");
if (this.__parent.config.CORE.devmode)
var url = "xml.php?"+path+"/.xml";
else
var url = "/"+path.split("/").splice(1,99).join("/")+"/.xml";
url = url.replace("//","/");
this.__parent.ajax.externalCall(this,'XML',url,'','cbLoadFolders');
}
this.cbLoadFolders = function(response) {
Debug.warning("modFolderList","cbLoadFolders","got backend response");
var response = Struct.render(response);
this.folders = this.sortFolders(response.folder[0].folder);
this.folders = this.filterFolders(this.folders);
this.lm.selected = 0;
this.lm.init();
if (this.activePath != null) {
this.setPath(this.activePath);
} else {
this.setPath(this.folders[0].name);
}
}
this.filterFolders = function(list) {
if (!list.length) return;
var newlist = [];
for(var i = 0;i<list.length; i++) {
var folder = list[i];
if (folder.title.substr(0,1) == "_") continue;
newlist[newlist.length] = folder;
}
return newlist;
}
this.sortFolders = function(list) {
var primary = new Array();
var secondary = new Array();
for (var i=0; i<list.length; i++) {
var folder = list[i];
if (folder.title.substr(0,1) == "_") continue;
if (folder.priority>0)
primary[primary.length] = folder;
else
secondary[secondary.length] = folder;
}
primary = Toolbox.object.sortObjectByProperty(primary,'priority',false);
secondary = Toolbox.object.sortObjectByProperty(secondary,'created',true);
var result = primary.concat(secondary);
return result;
}
this.setPath = function(path) {
this.activePath = path;
for(var i=0; i<this.folders.length; i++) {
if (this.folders[i].name == this.activePath) {
this.activeFolder = this.folders[i];
this.lm.selected = i;
}
}
this.__parent.config.saveQuery('path',this.activePath);
this.__parent.modHandler.updateEvent([{name:'new_content_path',value:this.activePath}]);
this.lm.init();
}
}
/**
* Module for presenting media files in a list
*
* @author Absoft AB
* @version 1.01
* @copyright Absoft AB, 24 January, 2007
* @package default
**/
var modMediaList = function(parent) {
this.__parent = parent;
this.moduleName = null;
var playIndex = null;
var playName = null;
var autoPlay = null;
var offset = null;
var playback = 'continuous';
this.currFileHash = '0';
this.currFileRunning = -1;
this.init = function() {
this.__parent.modHandler.module(this.moduleName).subscribe(0,['new_content_path','media_ended','skip']);
if (this.__parent.config.GET != undefined && this.__parent.config.GET.playindex != undefined)
this.playIndex = this.__parent.config.GET.playindex;
if (this.__parent.config.GET != undefined && this.__parent.config.GET.playfile != undefined)
this.playName = this.__parent.config.GET.playfile;
if (this.__parent.config.GET != undefined && this.__parent.config.GET.autoplay != undefined)
autoPlay = this.__parent.config.GET.autoplay;
if (this.__parent.config.GET != undefined && this.__parent.config.GET.autostart != undefined)
autoPlay = this.__parent.config.GET.autostart;
if (this.__parent.config.GET != undefined && this.__parent.config.GET.offset != undefined)
offset = this.__parent.config.GET.offset;
if (this.__parent.config.CORE != undefined && this.__parent.config.CORE.playback != undefined)
playback = this.__parent.config.CORE.playback;
}
this.eventReceiver = function(data) {
if (data["new_content_path"] != undefined) {
this.readMedia(data["new_content_path"]);
}
if (data["media_ended"]) {
if (playback == 'continuous') {
this.playNextFile();
}
if (playback == 'revert') {
this.setFile(this.currFile);
}
}
if (data["skip"]) {
if (data["skip"] == 1) {
this.playNextFile();
}
else if (data["skip"] == -1) {
this.playPrevFile();
}
}
}
this.readMedia = function(path) {
if (this.__parent.config.CORE.devmode)
var url = "xml.php?"+path+"/.xml";
else
var url = "/"+path.split("/").splice(1,99).join("/")+"/.xml";
url = url.replace("//","/");
this.lm = new Layout.manager(this);
this.lm.init();
if (this.lm && this.lm.setLoading)
this.lm.setLoading();
this.__parent.ajax.externalCall(this,'XML',url,'','cbLoadMedia');
}
this.folderItem = null;
this.cbLoadMedia = function(response) {
var data;
data = Struct.render(response);
data = data.folder[0];
data = this.filterFiles(data);
data.file = this.sortFiles(data.file);
if ((data.file != null) && (this.config.maxRowsLimit != null) && (this.config.maxRowsLimit < data.file.length))
data.file = data.file.slice(0,this.config.maxRowsLimit);
this.folderItem = data;
if (this.lm && this.lm.go)
this.lm.go(1);
if (this.playIndex != null) {
this.playFileByIndex(this.playIndex,data);
this.playIndex = null;
}
if (this.playName != null) {
this.playFileByName(this.playName,data);
this.playName = null;
}
}
this.sortFiles = function(list) {
if (typeof list != "object") return;
var primary = new Array();
var secondary = new Array();
for (var i=0; i<list.length; i++) {
var file = list[i];
if (file.priority>0)
primary[primary.length] = file;
else
secondary[secondary.length] = file;
}
primary = Toolbox.object.sortObjectByProperty(primary,'priority',false);
secondary = Toolbox.object.sortObjectByProperty(secondary,'pubfrom',true);
var result = primary.concat(secondary);
return result;
}
this.filterFiles = function(obj) {
if (!obj.file)
return obj;
var types = this.__parent.config.modMediaList.activeTypes;
var filterTypes = new Object();
var now=new Date();
var nowH=Toolbox.convert.checkLeadingZero(now.getHours());
var nowI=Toolbox.convert.checkLeadingZero(now.getMinutes());
var nowS=Toolbox.convert.checkLeadingZero(now.getSeconds());
var nowD=Toolbox.convert.checkLeadingZero(now.getDate());
var nowM=Toolbox.convert.checkLeadingZero(now.getMonth()+1);
var nowY=now.getYear();
if (nowY < 2000) nowY+=1900;
var nowTimestamp = ""+nowY+nowM+nowD+nowH+nowI+nowS;
for (var i=0;i<types.length;i++)
filterTypes[types[i]] = true;
for (var i=(obj.file.length-1);i>=0;i--) {
var skip = false;
var fileExt = obj.file[i]["URL"].split('.');
fileExt = fileExt[fileExt.length-1];
if (this.config.skipFilter != null)
skip = this.config.skipFilter.test(obj.file[i].name);
if (filterTypes[fileExt] != true)
skip = true;
if (obj.file[i].published < 1)
skip = true;
if ((obj.file[i].pubfrom > 0) && (obj.file[i].pubfrom > nowTimestamp)) {
if (obj.file[i].name != this.playName)
skip = true;
}
if ((obj.file[i].pubto > 0) && (obj.file[i].pubto < nowTimestamp))
skip = true;
if (skip)
obj.file.splice(i,1);
}
return obj;
}
this.playNextFile = function(index) {
if (this.folderItem.file[this.currFileRunning+1] == null)
return;
this.currFileRunning = ++this.currFileRunning;
var file = this.folderItem.file[this.currFileRunning];
this.__parent.modHandler.updateEvent([{name:'media_info',value:file}]);
this.setFile(file);
}
this.playPrevFile = function(index) {
if (this.folderItem.file[this.currFileRunning-1] == null)
return;
this.currFileRunning = --this.currFileRunning;
var file = this.folderItem.file[this.currFileRunning];
this.__parent.modHandler.updateEvent([{name:'media_info',value:file}]);
this.setFile(file);
}
this.lastMediaObject = {};
this.highlightObject = function() {
try {
this.lm.replaceTemplate(this.currFileRunning);
}
catch (e) {
}
}
this.playFileByIndex = function(index,data) {
var fileURL;
if (data.file[index] != undefined && data.file[index].URL != undefined)
fileURL = data.file[index].URL;
this.playFile(fileURL);
}
this.playFileByName = function(name,data) {
var fileURL;
if (data.file == null)
return;
for(var i=0; i<data.file.length; i++) {
if (data.file[i].name == name) {
fileURL = data.file[i].URL;
this.playFile(fileURL);
}
}
}
this.playFile = function(fileURL) {
var data = Toolbox.object.getObjectByProperty(this.folderItem.file,'URL',fileURL);
var file = data.object;
this.__parent.modHandler.updateEvent([{name:'controls_show_seekbar',value:true}]);
this.__parent.modHandler.updateEvent([{name:'media_info',value:file}]);
this.currFileRunning = data.index;
this.setFile(file);
}
this.setFile = function(file) {
this.currFile = file;
this.currFileHash = file.id;
this.highlightObject();
this.__parent.config.saveQuery('playfile',file.name);
if (autoPlay == 0) {
var videoWin = document.getElementById(this.__parent.config.PLAYER.playerWindowId);
var thumbnail = file.thumbnails[0].item;
var thumb = {src:thumbnail,w:videoWin.offsetWidth,h:videoWin.offsetHeight,url:file.URL};
this.__parent.modHandler.updateEvent([{name:'new_clicktoplay',value:thumb}]);
}
else {
if (offset) {
this.__parent.player.passedOffset = offset;
offset = null;
}
this.__parent.player.setFile(file);
}
}
}
/**
* Module for benchmarking visitor's bandwidth
*
* @author Absoft AB
* @version 1.00
* @copyright Absoft AB, 24 January, 2007
* @package default
**/
var modBandwidthTest = function(parent) {
this.__parent = parent;
this.moduleName = null;
this.init = function() {
Debug.warning("modBandwidthTest","init","started.");
this.defaultBitrate = this.config.defaultBitrate;
this.fallbackBitrate = this.config.fallbackBitrate;
this.setBitrate(this.defaultBitrate);
this.lm = new Layout.manager(this);
var testimg = new Image();
testimg.ref = this;
var test_st = new Date();
var test_et;
testimg.onload = function() {
test_et = new Date();
var res = (test_et.getTime() - test_st.getTime()) / 1000;
if (this.ref != null)
var objref = this;
else if (testimg.ref != null)
var objref = testimg;
var bw = objref.ref.calcBitrate(res);
objref.ref.setBitrate(bw);
objref.ref.runLayout();
}
testimg.src = this.lm.getURL('bwtest_'+this.config.testFileSize+'.jpg?'+test_st.getTime());
Debug.warning("modBandwidthTest","init","finished");
}
this.eventReceiver = function(data) {
}
this.calcBitrate = function(time) {
var size = this.config.testFileSize;
var bw = Math.round(size / time * 8 / 1024);
return bw;
}
this.setBitrate = function(bw) {
if (bw < this.defaultBitrate)
this.currentBitrate = this.fallbackBitrate;
else
this.currentBitrate = this.defaultBitrate;
this.setReplaceRule();
}
this.toggleBitrate = function() {
if (this.currentBitrate == this.defaultBitrate)
this.currentBitrate = this.fallbackBitrate;
else
this.currentBitrate = this.defaultBitrate;
this.runLayout();
this.setReplaceRule();
}
this.setReplaceRule = function() {
var fromBitrate = "_"+this.defaultBitrate+"k";
var toBitrate = "_"+this.currentBitrate+"k";
this.__parent.player.setReplaceRule(fromBitrate,toBitrate);
}
this.runLayout = function() {
this.lm.init();
}
}
/**
* Module for showing current media info
*
* @author Absoft AB
* @version 1.01
* @copyright Absoft AB, 24 January, 2007
* @package default
**/
var modTab_playing = function(parent) {
this.__parent = parent;
this.title = "Spelas just nu";
this.moduleName = null;
this.setNotice = null;
this.playlistObj = null;
this.playlistData = null;
this.playlistIndex = 0;
this.playlist = null;
this.clipIndex = null;
this.init = function() {
this.__parent.modHandler.module(this.moduleName).subscribe(0,['unknown_file_type','media_info',this.moduleName]);
this.lm = new Layout.manager(this);
if (this.__parent.config.GET != undefined && this.__parent.config.GET.clipindex != undefined) {
this.clipIndex = parseInt(this.__parent.config.GET.clipindex);
this.playlistIndex = parseInt(this.__parent.config.GET.clipindex);
}
this.lm.init();
}
this.active = false;
this.eventReceiver = function(data) {
if (data[this.moduleName] == true) {
this.active = true;
}
if (data[this.moduleName] == false) {
this.active = false;
}
if (data["unknown_file_type"]) {
var fileExt = Toolbox.getFileExt(data["unknown_file_type"].URL);
if (fileExt != "pls") return;
this.__parent.modHandler.module(this.moduleName).subscribe(1,['media_ended','skip','set_clip']);
this.loadPlaylist(data["unknown_file_type"].URL);
}
if (data["media_ended"]) {
if (this.playlistObj != null)
this.setClip((this.playlistIndex+1),0);
}
if (data["skip"]) {
if (data["skip"] == 1)
this.nextClip();
else if (data["skip"] == -1)
this.prevClip();
}
if (data["media_info"]) {
if (data["media_info"].type == "text/xml") {
this.playlistData = data["media_info"];
this.mediaData = null;
} else {
this.playlistData = null;
this.playlistObj = null;
this.mediaData = data["media_info"];
}
}
if (data["set_clip"]) {
this.setClip(data["set_clip"],-1);
}
if (this.active) {
this.lm.response = this.playlistObj;
this.lm.mediaData = this.mediaData;
this.lm.writeData();
}
}
this.loadPlaylist = function(playlist) {
if (this.__parent.config.CORE.devmode)
var url = "xml.php?"+playlist;
else {
playlist = playlist.replace("http://","");
var url = "/"+playlist.split("/").splice(1,99).join("/");
url = url.replace("//","/");
}
this.__parent.ajax.externalCall(this,'XML', url,'','cbLoadPlaylist');
}
this.cbLoadPlaylist = function(response,txt) {
var data;
data = Struct.render(response);
this.playlistIndex = 0;
if (this.clipIndex != null) {
this.playlistIndex = this.clipIndex;
this.clipIndex = null;
}
var obj = Toolbox.object.dump(data,'<br>');
if ((data.playlist != null) && (data.playlist[0].clip != null))
{
this.playlist = data.playlist;
this.playlistObj = data.playlist[0].clip;
this.setClip(this.playlistIndex,-1);
}
}
this.prevClip = function() {
var newIndex = this.playlistIndex-1;
this.setClip(newIndex,-1);
}
this.nextClip = function() {
var newIndex = this.playlistIndex+1;
this.setClip(newIndex, 1);
}
this.setClip = function(index, onCommercial) {
this.playlistIndex = index;
if (this.playlistObj == null)
return;
var prevClip = this.playlistObj[this.playlistIndex-1];
if ((prevClip != null) && (prevClip.mode == "commercial")) {
var tmp = this.playlistIndex + onCommercial;
this.playlistIndex  = tmp;
}
if (this.playlistObj[this.playlistIndex] != null) {
this.runPlaylist();
} else {
this.__parent.modHandler.module(this.moduleName).unsubscribe(1,['media_ended','skip']);
this.playlistIndex = 0;
if (onCommercial == 1)
this.__parent.modHandler.updateEvent([{name:'media_ended',value:true}]);
}
}
this.runPlaylist = function() {
var file = this.playlistObj[this.playlistIndex];
this.__parent.modHandler.updateEvent([{name:'current_playlist_obj',value:{playlist:this.playlistObj,clip:this.playlistIndex}}]);
this.__parent.modHandler.updateEvent([{name:'current_obj_data',value:{playlist:this.playlistData,clip:this.playlistIndex}}]);
this.__parent.modHandler.updateEvent([{name:'playlist_clip_data',value:file}]);
this.__parent.modHandler.updateEvent([{name:'current_playlist',value:this.playlist}]);
if (this.playlistObj[this.playlistIndex].mode == 'regular')
this.__parent.modHandler.updateEvent([{name:'controls_show_seekbar',value:true}]);
if (this.playlistObj[this.playlistIndex].mode == 'commercial')
this.__parent.modHandler.updateEvent([{name:'controls_show_seekbar',value:false}]);
this.__parent.config.saveQuery('clipindex',this.playlistIndex);
this.__parent.player.setFile(file);
if (this.active) {
this.lm.response = this.playlistObj;
this.lm.writeData();
}
}
}
var modTab_tipFriend = function(parent) {
this.title = "Dela filmen";
this.__parent = parent;
this.moduleName = null;
this.mediaInfo = null;
this.currid = null;
this.setNotice = null;
this.init = function() {
this.__parent.modHandler.module(this.moduleName).subscribe(0,[this.moduleName,'media_info']);
this.lm = new Layout.manager(this);
}
this.eventReceiver = function(data) {
if (data[this.moduleName] == true) {
this.active = true;
var paramlist = [];
var params = this.__parent.config.getQuery();
params["autoplay"] = 1;
for(name in params) {
paramlist[paramlist.length] = name+"="+params[name];
}
var query = paramlist.join("&");
this.currPlayerPath = this.__parent.config.CORE.playerFile + "?" + query;
} else if (data[this.moduleName] == false) {
this.active = false;
}
if (data['media_info']) {
this.mediaInfo = data['media_info'];
if ($('tipFriendShareByLink') ) {
$('tipFriendShareByLink').value = '';
var ref = this;
window.setTimeout(function() {
$('tipFriendShareByLink').value = ref.getPlayerUrl('&');
},500);
}
}
if (this.active) {
if (this.mediaInfo && this.mediaInfo.id != null)
this.currid = this.mediaInfo.id;
try {
this.lm.setContent();
}
catch (e) {
}
}
}
this.path = null;
this.getPlayerUrl = function(queryseparator) {

if (!this.mediaInfo)
	return null;

if (!queryseparator)
queryseparator = '&';
var q = this.__parent.config.getQuery();
delete q['offset'];
q['volume'] = 50;
var pl = [];
q['path'] = this.mediaInfo.path;
for(name in q) {
pl[pl.length] = name+"="+q[name];
}
var query = pl.join(queryseparator);
var l = document.location.href.split('?')[0];
l = 'http://oatv.abcdn.net/abPlayer2/default.html';
var path = l+"?"+query;
return path;
}
this.makeCallExternal = function(ex) {
var queryseparator = '&';
if (ex == 'facebook') // Special for facebook
	queryseparator = '||';

var path = this.getPlayerUrl(queryseparator);

if (path == null)
	return;

var title = this.mediaInfo.title;
var desc = this.mediaInfo.desc;
if (!title)
	title='';
if (!desc)
	desc='';
var thumb = 'http://'+this.mediaInfo.thumbnails[0].item;
if (ex == 'pusha') {
u = 'http://www.pusha.se/posta?url='+encodeURIComponent(path)+'&title='+escape(title)+'&description='+escape(desc);
window.open(u);
}
if (ex == 'magnolia') {
u = 'http://ma.gnolia.com/bookmarklet/add?url='+encodeURIComponent(path)+'&title='+title+'&description='+desc;
window.open(u);
}
if (ex == 'stumbleupon') {
u = 'http://www.stumbleupon.com/submit?url='+encodeURIComponent(path)+'&title='+escape(title)+'&newcomment='+escape(desc);
window.open(u);
}
if (ex == 'digg') {
u = 'http://digg.com/submit?phase=2&url='+encodeURIComponent(path)+'&title='+title+'&bodytext='+desc;
window.open(u);
}
if (ex == 'delicious') {
//u = 'http://digg.com/submit?phase=2&url='+encodeURIComponent(path)+'&title='+title+'&bodytext='+desc;
u = 'http://del.icio.us/post?url='+ encodeURIComponent(path)+';title='+desc;
window.open(u);
}
if (ex == 'facebook') {

u = 'http://www.facebook.com/share.php?u='+
encodeURIComponent(
'http://api.abcdn.net/apps/facebook/facebook_proxy.php?'+
'thumb='+thumb+
'&title='+title+
'&desc='+desc+
'&url='+ encodeURIComponent(path)+ 
'&seed='+(Math.round(Math.random()*10000))
);

window.open(u,'sharer');

}
}
this.makeCall = function() {
var tip_to_email	= document.getElementById('tipfriend_to_mail').value;
var tip_from_email	= document.getElementById('tipfriend_from_mail').value;
var tip_from_name	= document.getElementById('tipfriend_from_name').value;
var tip_message		= document.getElementById('tipfriend_message').value;
var validate = this.lm.validate();
if (validate.error) {
var errMsg = validate.error;
var sendObj = {visible:true,template:'coverMessageDialogueOk',head:'Felmeddelande',message:errMsg,module:this.moduleName };
this.__parent.modHandler.updateEvent( [ {name:'tab_notice',value:sendObj} ],true );
return;
}
if (this.currid == null) {
var sendObj = {visible:true,template:'coverMessageDialogueOk',head:'Felmeddelande',message:'Du m&aring;ste p&aring;b&ouml;rja en uppspelning f&ouml;r att kunna tipsa en v&auml;n.',module:this.moduleName };
this.__parent.modHandler.updateEvent( [ {name:'tab_notice',value:sendObj} ],true );
return;
}
var tip_data = this.currid;
var post="tipsterName="+tip_from_name+"&tipsterEmail="+tip_from_email+"&friendEmail="+tip_to_email+"&tipData="+tip_data+"&description="+tip_message;
/*
method:		(string) post/get
url:		(string) [ http:// ]url
callback:	(string) cbFunction
reference:	(Object) ref
*/
var call = { method:	'post',
postBody:	post,
url:		this.config.backendURL,
callback:	'cbMakeCall',
reference:	this
}
var sendObj = {visible:true,template:'coverMessageNotice',head:'Meddelande',message:'Skickar tips till '+tip_to_email,module:this.moduleName };
this.__parent.modHandler.updateEvent( [ {name:'tab_notice',value:sendObj} ],true );
this.__parent.ajax.externalCall2(call);
}
this.cbMakeCall = function(transport,json) {


//response = eval('(' + transport.responseText + ')');

// Bypass proxy callback.

response = null;

var g=[];

//var status = response['@attributes']['stat'];
var errorCode,errorMessage;
var sendObj = null;

if (response && response['err']) {
 if (response['err']['@attributes']['code'] == 3) {
 this.lm.validate();
 sendObj = {visible:true,template:'coverMessageDialogueOk',head:'Felmeddelande',message:response['err']['@attributes']['msg'],module:this.moduleName};
 }
 else {
 sendObj = {visible:true,template:'coverMessageDialogueOk',head:'Felmeddelande',message:'Ett tekniskt fel har uppst&aring;tt..',module:this.moduleName};
 }
}
else {
 sendObj = {visible:true,template:'coverMessageDialogueOk',head:'Meddelande',message:'Meddelandet skickades iv&auml;g!',module:this.moduleName};
 if (this.mediaInfo && this.mediaInfo.id != null) {
  this.currid = this.mediaInfo.id;
 }
}

if (sendObj != null)
this.__parent.modHandler.updateEvent( [ {name:'tab_notice',value:sendObj} ],true );
}
}
/**
* Module for managing tabs
*
* @author Absoft AB
* @version 1.01
* @copyright Absoft AB, 24 January, 2007
* @package default
**/
var modTabs = function(parent) {
this.__parent = parent;
this.moduleName = null;
this.tabList = {}
this.selectedTab = null;
this.tabModules = [];
this.init = function() {
this.__parent.modHandler.module(this.moduleName).subscribe(0,['tab_notice']);
var tabPrefix = this.config.tabPrefix;
for (var i=0;i<this.__parent.config.CORE.loadModules.length;i++) {
var isTab = (this.__parent.config.CORE.loadModules[i].indexOf(tabPrefix)>-1);
if (isTab) {
var module = this.__parent.config.CORE.loadModules[i];
this.tabModules[this.tabModules.length] = module;
this.tabList[module] = this.__parent.modHandler.getModule(module).title;
}
}
this.lm = new Layout.manager(this);
this.lm.init();
this.lm.writeTabs();
this.lm.createTabContent();
for (var i=0;i<this.tabModules.length;i++){
try{
this.__parent.modHandler.getModule(this.tabModules[i]).lm.init();
}
catch(e){
}
}
this.openTabByIndex(0);
}
this.eventReceiver = function(data) {
if (data['tab_notice']) {
this.lm.setNotice(data['tab_notice']);
}
}
this.openTabByIndex = function(idx) {
for (var i=0;i<this.tabModules.length;i++) {
var cond = false;
if (i==idx)
cond = true;
var e = (cond ? 'Effect.Appear' : 'Element.hide');
eval(e+'("'+'div_container_'+this.tabModules[i]+'")');
this.__parent.modHandler.updateEvent([{name:this.tabModules[i],value:cond}]);
}
this.selectedTab = this.tabModules[idx];
this.lm.writeTabs();
}
this.openTab = function(module) {
for (var i=0;i<this.tabModules.length;i++) {
if (module == this.tabModules[i]) {
this.openTabByIndex(i);
break;
}
}
}
}
var templates = {};
templates.modLiveStream = {};
templates.modControls = {};
templates.modControls['modControls.xml'] = '<?xml version="1.0" encoding="UTF-8"?>\n'+
'<templates>\n'+
'	<template name="playerData"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'			\n'+
'	<div id="playerData"  style=""><!-- --></div>\n'+
'\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="fullscreen"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'				<div style="float:left;width:43px;">\n'+
'					<img src="<<this.getURL(\'fullscreen.gif\')>>" onclick="openFullscreen(eval(<<#>>.__parent.__instance))" style="cursor:pointer;"/>\n'+
'				</div>\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="volume"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'		<div id="playerVolumeContainer" style="width:74px;position:relative;float:left;">			\n'+
'			\n'+
'						<div id="volMinus" onclick="<<$>>.goVolume(-10);" style="float:left;cursor:pointer;width:37px;height:16px;background:url(<<this.getURL(\'vol_minus.gif\')>>);"><!-- --></div>\n'+
'			\n'+
'						<div id="volPlus" onclick="<<$>>.goVolume(10);" style="float:left;cursor:pointer;width:37px;height:16px;background:url(<<this.getURL(\'vol_plus.gif\')>>);"><!-- --></div>\n'+
'			\n'+
'		</div>\n'+
'		\n'+
'		\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="playButton"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'					<div onclick="<<#>>.__parent.player.pauseMedia()" style="cursor:pointer;background-repeat:no-repeat;float:left;position:relative;height:16px;width:35px;background:url(<<this.getURL(\'pause.gif\')>>);margin-right:5px" id="playButton"><!-- --></div>\n'+
'\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="pauseButton"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'					<div onclick="<<#>>.__parent.player.playMedia()" style="cursor:pointer;float:left;background:url(<<this.getURL(\'play.gif\')>>);background-repeat:no-repeat;position:relative;height:16px;width:35px;margin-right:5px" id="pauseButton"><!-- --></div>\n'+
'\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="fullscreenButton"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'					<div onclick="<<#>>.__parent.player.toggleFullscreen()" id="fullscreenButton"><img src="<<this.getURL(\'button_fullscreen.gif\')>>"></div>\n'+
'\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'		<template name="closeFullscreenButton"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'					<div onclick="<<#>>.__parent.player.toggleFullscreen()" id="closeFullscreenButton"><img src="<<this.getURL(\'button_fullscreen.gif\')>>"></div>\n'+
'\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="progressbar"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'					<div id="playerProgressBar" style="float:left;position:relative;height:16px;width:218px;background-image:url(<<this.getURL(\'progressbarbg.gif\')>>);background-repeat:no-repeat;"> \n'+
'						<img id="playerHandle" src="<<this.getURL(\'seekhandle.gif\')>>" style="cursor:move;position:absolute;width:16px;height:16px;"/>\n'+
'					</div>\n'+
'\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="playerTime"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'					<div id="playerTime" onclick="<<#>>.nextTimeMode();" style="cursor:pointer;position:relative;float:left;width:72px;font-family:Arial;font-size:10px;padding-top:3px;text-align:center;">\n'+
'				&nbsp;&nbsp;\n'+
'					</div>\n'+
'\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'		<template name="skip"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'			\n'+
'				<div style="float:left;width:60px;height:16px;">\n'+
'					\n'+
'						<img id="playerSkipPrevHandle" onclick="<<#>>.skip(-1)" style="cursor:pointer" src="<<this.getURL(\'skip_prev.gif\')>>"/><img id="playerSkipNextHandle" onclick="<<#>>.skip(1)" style="cursor:pointer;" src="<<this.getURL(\'skip_next.gif\')>>"/>\n'+
'					\n'+
'				</div>\n'+
'\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	\n'+
'		<template name="playPause"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'				<div id="playerPlayPauseContainer" style="float:left;width:42px;height:16px">\n'+
'			\n'+
'				</div>\n'+
'\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'</templates>';
templates.modBanner = {};
templates.modTabList = {};
templates.modTabList['modTabList.xml'] = '<?xml version="1.0" encoding="UTF-8"?>\n'+
'<templates>\n'+
'	<template name="header"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'<div style="margin:0px;overflow:hidden;border-top:1px solid #d8dfe8;">\n'+
'			<div style="overflow: hidden; background-image:url(<<this.getURL(\'folder_bg.gif\')>>); height: 8px; position: relative; background-position: left top; line-height: 0px;"><!-- --></div>\n'+
'			<div style="overflow:hidden;padding:0px 0px 0px 4px;background-color:#f6f9fd">\n'+
'	\n'+
'    		]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="footer"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'			</div>\n'+
'		<div style="overflow: hidden; background-image:url(<<this.getURL(\'folder_bg.gif\')>>); height: 8px; position: relative; background-position: left bottom; line-height: 0px;"><!-- --></div>\n'+
'       </div>\n'+
'\n'+
'			\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="folderItem"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'		<div style="cursor:pointer;font-weight:normal;color:#939aa7;float:left;padding:0px 5px 0px 5px;">\n'+
'			<div onclick="<<$>>.selected=<<this.i>>;<<#>>.setPath(\'<<this.data.name>>\')"><nobr><nobr><<this.title>></nobr></nobr></div>\n'+
'		</div>\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="folderItemActive"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'		<div style="cursor:default;font-weight:bold;color:#000000;float:left;padding:0px 5px 0px 5px;background-repeat:no-repeat;background-image:url(<<this.getURL(\'folder_arrow.gif\')>>);background-position:center left">\n'+
'			<div onclick="<<$>>.selected=<<this.i>>;<<#>>.setPath(\'<<this.data.name>>\')"><nobr><nobr><<this.title>></nobr></nobr></div>\n'+
'		</div>\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'</templates>';
templates.modTab_tipFriend = {};
templates.modTab_tipFriend['modTab_tipFriend.xml'] = '<?xml version="1.0" encoding="UTF-8"?>\n'+
'<templates>\n'+
'	<template name="content"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'				<div id="tipFriendContent" style="position:relative;width:510px;height:146px;overflow:hidden;">\n'+
'\n'+
'	    			<div style="float:left;width:96px;padding:9px;margin:0px;background-color:#FFFFFF;">\n'+
'    					<div style="height:16px;width:96px;">Tipsa om:</div><span id="tipFriendThumb"></span><div id="tipFriendTitle" style="color:#30394a;font-family:Verdana;font-weight:bold;width:96px;"><!-- --></div>\n'+
'	    	        </div>\n'+
'	    	        \n'+
'	    	        <div style="float:left;padding-top:4px;padding-right:0px;width:380px;">\n'+
'	    	        	\n'+
'    	    	        <div style="float:left;background-color:#bfd5f8;width:380px;height:138px;padding:3px;">\n'+
'	    	        \n'+
'    		    	        <div style="border:1px outset #dae5f8;float:left;padding:5px;width:230px;height:124px;margin-right:2px;background-color:#dae5f8">\n'+
'			        \n'+
'    							\n'+
'    								<!-- head -->\n'+
'    								\n'+
'    								<div style="font-size:10px;border-bottom:1px solid #c0cadb;width:100%">Via e-post</div>\n'+
'    								\n'+
'    								<!-- // head -->\n'+
'    							\n'+
'    								<div class="tipFriendBox" style="margin-top:5px;margin-bottom:5px;overflow:hidden">\n'+
'    									\n'+
'    									<div style="float:left">\n'+
'    									<div id="tipfriend_to_mail_container">\n'+
'    										Mottagarens e-post<br><input id="tipfriend_to_mail" type="text" style="width:100px;font-size:10px">\n'+
'    									</div>\n'+
'    									\n'+
'    									<div style="margin-top:2px">\n'+
'    										Ditt meddelande<br>\n'+
'            								<textarea id="tipfriend_message" style="font-size:10px;width:100px;height:40px;font-family:Verdana;"></textarea>\n'+
'            							</div>\n'+
'            							\n'+
'    									</div>\n'+
'\n'+
'                                        <div style="float:right;overflow:hidden">\n'+
'											\n'+
'											<!-- buttons -->\n'+
'                                            <div>\n'+
'            								    \n'+
'            								    <div id="tipfriend_from_name_container">\n'+
'            									    Ditt namn<br><input id="tipfriend_from_name" type="text" style="width:100px;padding:0px;font-size:10px">\n'+
'            								    </div>\n'+
'            								</div>\n'+
'            								<div  style="margin-top:2px">\n'+
'            									\n'+
'            									<div id="tipfriend_from_mail_container">\n'+
'            										Din e-post<br><input id="tipfriend_from_mail" type="text" style="width:100px;padding:0px;font-size:10px">\n'+
'            									</div>\n'+
'            								</div>\n'+
'            								\n'+
'            								<div style="margin-top:10px;">\n'+
'            								<img src="<<this.getURL(\'button_send2.gif\')>>" onclick="<<#>>.makeCall()" style="cursor:pointer">\n'+
'            								</div>\n'+
'            							\n'+
'                                        </div>\n'+
'\n'+
'            							\n'+
'    								</div>\n'+
'    								\n'+
'    								<div style="overflow:hidden">\n'+
'            							\n'+
'            							\n'+
'            							\n'+
'            							</div>\n'+
'    							\n'+
'    							<div style="clear:both"><!-- --></div>\n'+
'							\n'+
'    						</div>\n'+
'    						\n'+
'    						<!-- right -->\n'+
'    						\n'+
'    						\n'+
'    						\n'+
'    						<div style="float:right;width:130px;">\n'+
'    							\n'+
'    							\n'+
'    							<div style="border:1px outset #dae5f8;background-color:#dae5f8;padding:5px;background-color:#dae5f8;height:56px">\n'+
'    								<div style="font-size:10px;border-bottom:1px solid #c0cadb;margin-bottom:10px">Via l&auml;nk</div>\n'+
'								<div style="font-size:9px">OBS, kopiera hela l&auml;nken</div>\n'+
'    								<input id="tipFriendShareByLink" type="text" style="width:95%;font-size:9px;">\n'+
'    						\n'+
'    							</div>\n'+
'    							\n'+
'    								\n'+
'    							<div style="font-size:11px;border:1px outset #dae5f8;background-color:#dae5f8;padding:5px;margin-top:2px;height:53px">\n'+
'    								<div style="border-bottom:1px solid #c0cadb;margin-bottom:15px">Via sociala n&auml;tverk</div>\n'+
'    								\n'+
'    									\n'+
'    								\n'+
'    								<img style="cursor:pointer" onclick="<<#>>.makeCallExternal(\'facebook\')" src="<<this.getURL(\'icon_facebook.gif\')>>">\n'+
'    								<img onclick="<<#>>.makeCallExternal(\'digg\')" src="http://digg.com/img/badges/16x16-digg-guy.gif"  style="cursor:pointer">\n'+
'    								<img onclick="<<#>>.makeCallExternal(\'stumbleupon\')" src="<<this.getURL(\'icon_stumbleupon.gif\')>>" style="cursor:pointer">\n'+
'    								<img onclick="<<#>>.makeCallExternal(\'delicious\')" src="http://images.del.icio.us/static/img/delicious.gif" width="16" height="16" style="cursor:pointer" >\n'+
'    								<img onclick="<<#>>.makeCallExternal(\'magnolia\')" src="<<this.getURL(\'icon_magnolia.png\')>>" width="16" height="16" style="cursor:pointer" >\n'+
'    								<img onclick="<<#>>.makeCallExternal(\'pusha\')" src="http://pusha.se/pics/pusha_16_16.gif" width="16" height="16" style="cursor:pointer" >\n'+
'    								\n'+
'    								\n'+
'    							</div>\n'+
'   								\n'+
'    						\n'+
'    							\n'+
'    							\n'+
'    						\n'+
'    							\n'+
'    						</div>\n'+
'						\n'+
'        					<div style="clear:both"><!-- --></div>\n'+
'						\n'+
'    					</div>\n'+
'				    </div>\n'+
'				</div>\n'+
'\n'+
'    		]]>\n'+
'		</html>\n'+
'	</template>\n'+
'</templates>';
templates.modMediaList = {};
templates.modMediaList['modMediaList.xml'] = '<?xml version="1.0" encoding="UTF-8"?>\n'+
'<templates>\n'+
'	<template name="normalFile"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'			\n'+
'<div onclick="<<#>>.playFile(\'<<this.data.URL>>\',<<this.currPos>>);" id="media_<<this.currPos>>" style="\n'+
'			width:297px;\n'+
'			height:70px;\n'+
'			<<this.css>>;\n'+
'			margin-top:10px;\n'+
'			margin-left:8px;\n'+
'			font-size:10px;\n'+
'			font-family:Verdana;\n'+
'			position:relative;\n'+
'			background-color:<< this.background >>;\n'+
'			cursor:pointer;">\n'+
'	<< this.image >>\n'+
'	<div style="overflow:hidden;width:180px;height:70px;padding-left:8px;padding-right:8px;">\n'+
'		<div style="color:#30394a;font-weight:bold;padding-top:2px;padding-bottom:2px;">\n'+
'			<<(this.data.title).truncate(25)>> \n'+
'		</div>\n'+
'		<div style="color:#000000;line-height:13px;">\n'+
'			<< ((this.data.desc) ? this.data.desc : "").truncate(55) >>\n'+
'		</div>\n'+
'		<div style="color:<< this.datecolor >>">\n'+
'			<< this.date >>\n'+
'		</div>\n'+
'		<span style="color:#003399;padding-right:10px;background-repeat:no-repeat;background-image:url(<<this.getURL(\'folder_arrow.gif\')>>);background-position:center right">\n'+
'			Se inslaget\n'+
'		</span>\n'+
'	</div>\n'+
'	\n'+
'</div>\n'+
'\n'+
'	\n'+
'\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="activeFile"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'			\n'+
'<div onclick="<<#>>.playFile(\'<<this.data.URL>>\',<<this.currPos>>);" id="media_<<this.currPos>>" style="\n'+
'			width:297px;\n'+
'			height:70px;\n'+
'			<<this.css>>;\n'+
'			padding-top:10px;\n'+
'			padding-left:8px;\n'+
'			font-size:10px;\n'+
'			font-family:Verdana;\n'+
'			position:relative;\n'+
'			background-color:#FFFFFF;\n'+
'			background-image:url(<<this.getURL(\'active_topbg.gif\')>>);\n'+
'			background-repeat:no-repeat;\n'+
'			background-position:top left;\n'+
'			cursor:pointer;">\n'+
'	<< this.image >>\n'+
'	<div style="overflow:hidden;width:180px;height:70px;padding-left:8px;padding-right:8px;">\n'+
'		<div style="color:#30394a;font-weight:bold;padding-top:2px;padding-bottom:2px;">\n'+
'			<<(this.data.title).truncate(25)>> \n'+
'		</div>\n'+
'		<div style="color:#000000;line-height:13px;">\n'+
'			<< ((this.data.desc) ? this.data.desc : "").truncate(55) >>\n'+
'		</div>\n'+
'		<div style="color:<< this.datecolor >>">\n'+
'			<< this.date >>\n'+
'		</div>\n'+
'		<span style="color:#003399;padding-right:10px;background-repeat:no-repeat;background-image:url(<<this.getURL(\'folder_arrow.gif\')>>);background-position:center right">\n'+
'			Se inslaget\n'+
'		</span>\n'+
'	</div>\n'+
'	<div style="left:0px;z-index:1;height:10px;width:297px;position:absolute;bottom:-10px;background-image:url(<<this.getURL(\'active_bottombg.gif\')>>);background-repeat:repeat-x;background-position:bottom left;"><!-- --></div>\n'+
'</div>\n'+
'\n'+
'	\n'+
'\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>	\n'+
'	<template name="loading"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'			\n'+
'			\n'+
'<div class="greenBorder" style="display: table; height: 480px;width:297px;  #position: relative; overflow: hidden;">\n'+
'	<div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;width:297px;text-align:center">\n'+
'		<div class="greenBorder" style=" #position: relative; #top: -50%;">\n'+
'        	\n'+
'        	<img src="<<this.getURL(\'ajax-loader.gif\')>>" >\n'+
'        	<br>\n'+
'        	Laddar meny..\n'+
'		</div>\n'+
'	</div>\n'+
'</div>		\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	\n'+
'	<template name="containerStart"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'<div style="position:relative;width:305px;height:490px;overflow:hidden;" id="dragContainer">\n'+
'	\n'+
'	<div style="position:absolute" id="dragContent">\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="containerEnd"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'</div></div>\n'+
'<div style="clear:both"></div>\n'+
'\n'+
'<div style="padding-top:0px;width:305px;height:20px;z-index:999;background-color:#FFFFFF;">\n'+
'		<div style="padding-left:120px;">\n'+
'			<div style="float:left;" onclick="<<$>>.go(-1);"><img src="<<this.getURL(\'scrollup.gif\')>>" width="18" height="18" style="cursor:pointer;"/></div>\n'+
'			<div id="count" style="height:18px;width:35px;float:left;font-family:Verdana;font-size:10px;color:#636a77;line-height:18px;text-align:center;"></div>\n'+
'			<div style="float:left;" onclick="<<$>>.go(1);"><img src="<<this.getURL(\'scrolldown.gif\')>>" width="18" height="18" style="cursor:pointer;"/></div>\n'+
'			<div style="clear:both;"><!-- --></div>\n'+
'		</div>\n'+
'		\n'+
'	</div>\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	\n'+
'</templates>';
templates.modBandwidthTest = {};
templates.modTab_playing = {};
templates.modTab_playing['modTab_playing.xml'] = '<?xml version="1.0" encoding="UTF-8"?>\n'+
'<templates>\n'+
'	<template name="activeClip"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'			\n'+
'				<div onmouseover="<<$>>.sendHoverEvent(this,<<this.i>>,\'bottom2\');" onmouseout="<<$>>.sendHoverOutEvent(this)" onclick="<<$>>.runClip(<<this.i>>)" style="margin:3px;cursor:pointer;width:67px;height:59px;float:left;background:url(<<this.getURL(\'activeclipbg.gif\')>>);"><img src="<<this.thumb>>" hspace="3" vspace="3" width="61" height="46" style="padding-top:7px;"></div>\n'+
'\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="inactiveClip"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'				<div onmouseover="<<$>>.sendHoverEvent(this,<<this.i>>,\'bottom2\');" onmouseout="<<$>>.sendHoverOutEvent(this)" onclick="<<$>>.runClip(<<this.i>>)" style="margin:3px;cursor:pointer;width:67px;height:59px;float:left;"><img src="<<this.thumb>>" hspace="3" vspace="3" width="61" height="46" style="padding-top:7px;"></div>\n'+
'				\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="clipText"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'				\n'+
'				<div style="clear:both"><!-- --></div>\n'+
'				<div style="font-family:Verdana;font-size:18px;font-weight:bold;padding:3px;"><<this.playlistData.title>></div>\n'+
'				<div style="font-family:Verdana;font-size:11px;padding:3px;"><< (this.playlistData.desc != undefined) ? this.playlistData.desc : "" >></div>\n'+
'				\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="noClipRunning"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'				\n'+
'				<div style="clear:both"><!-- --></div>\n'+
'				<div style="font-family:Verdana;font-size:11px;padding:15px;">F&ouml;r att b&ouml;rja titta, v&auml;lj en film i spellistan till h&ouml;ger!</div>\n'+
'				\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="mediaText"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'				\n'+
'				<div style="clear:both"><!-- --></div>\n'+
'				<div style="font-family:Verdana;font-size:18px;font-weight:bold;padding:3px;"><<this.mediaData.title>> </div>\n'+
'				<div style="font-family:Verdana;font-size:11px;padding:3px;"><< (this.mediaData.desc != undefined) ? this.mediaData.desc : "" >></div>\n'+
'				\n'+
'			]]>\n'+
'		</html>\n'+
'	</template>\n'+
'</templates>';
templates.modTabs = {};
templates.modTabs['modTabs.xml'] = '<?xml version="1.0" encoding="UTF-8"?>\n'+
'<templates>\n'+
'\n'+
'	<template name="flikWrapperStart"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'				<div style="height:20px;background-image:url(<<this.getURL(\'tab_bg_inactive.gif\')>>);">\n'+
'\n'+
'    		]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="flikWrapperEnd"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'				</div>\n'+
'\n'+
'    		]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="flik"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'				<div onclick="<<#>>.openTab(\'<<this.id>>\')" id="<<this.id>>" style="padding-left:25px;padding-right:25px;cursor:pointer;line-height:18px;font-weight:normal;font-size:10px;height:20px;font-family:Verdana;background-image:url(<<this.getURL(\'tab_bg_inactive.gif\')>>);float:left;color:#30394a;">\n'+
'					<<this.title>>\n'+
'				</div>\n'+
'\n'+
'    		]]>\n'+
'		</html>\n'+
'	</template>\n'+
'		<template name="flikActive"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'				<div id="<<this.id>>" style="cursor:default;padding-left:25px;padding-right:25px;line-height:18px;font-weight:normal;font-size:10px;height:20px;font-family:Verdana;background-image:url(<<this.getURL(\'tab_bg_active.gif\')>>);color:#30394a;float:left">\n'+
'					<<this.title>>\n'+
'				</div>\n'+
'\n'+
'    		]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="separatorActive"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'				<div id="<<this.id>>" style="height:20px;float:left;width:1px;background-color:#d8dfe8">\n'+
'					<!-- -->\n'+
'				</div>\n'+
'\n'+
'    		]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="separator"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'				<div id="<<this.id>>" style="height:20px;float:left;width:1px;background-color:#d8dfe8">\n'+
'					<!-- -->\n'+
'				</div>\n'+
'\n'+
'    		]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="separatorEnd"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'\n'+
'				<div id="<<this.id>>" style="height:20px;float:right;width:1px;background-color:#d8dfe8">\n'+
'					<!-- -->\n'+
'				</div>\n'+
'\n'+
'    		]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="coverMessageNotice"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'				<div style="width:250px">\n'+
'    				<div><<this.noticeMessage>></div>\n'+
'				</div>\n'+
'\n'+
'    		]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="coverMessageDialogueOk"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'			\n'+
'				<div style="position:relative;width:250px">\n'+
'	    			\n'+
'					<div><<this.noticeMessage>></div>\n'+
'	    			<br>\n'+
'	    			\n'+
'	    			<div style="text-align:center;">\n'+
'	    				<img src="<<this.getURL(\'button_ok.gif\')>>"  onclick="<<$>>.setNotice( {visible:false,module:\'<<this.moduleName>>\'} )" style="cursor:pointer;" class="button">\n'+
'\n'+
'					</div>\n'+
'					\n'+
'				</div>\n'+
'				<div style="clear:both"><!-- --></div>\n'+
'				\n'+
'    		]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="coverTerms"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'			\n'+
'				<div style="position:relative;width:400px;">\n'+
'					\n'+
'	    			\n'+
'					<div style="border:1px solid gray;width:400px;height:76px;overflow:auto"><<this.noticeMessage>></div>\n'+
'					<div style="line-height:6px;height:6px;"><!-- --></div>\n'+
'	    			<div style="clear:both"><!-- --></div>\n'+
'	    		\n'+
'	    			<div style="text-align:center;">\n'+
'	    				<img src="<<this.getURL(\'button_ok.gif\')>>"  onclick="<<$>>.setNotice( {visible:false,module:\'<<this.moduleName>>\'} )" style="cursor:pointer;" class="button">\n'+
'\n'+
'					</div>\n'+
'					\n'+
'					\n'+
'				</div>\n'+
'				<div style="clear:both"><!-- --></div>\n'+
'				\n'+
'    		]]>\n'+
'		</html>\n'+
'	</template>\n'+
'	<template name="tabPlaceHolder"\n'+
'		><html\n'+
'			><![CDATA[\n'+
'				\n'+
'				<div style="position:relative;width:512px;height:146px;" id="<<this.divContainerId>>">\n'+
'				\n'+
'					<div style="position:absolute;visibility:hidden;z-index:999" id="<<this.divMessageContainerId>>">\n'+
'					\n'+
'						<div id="<<this.divMessageCoverId>>" style="background-color:white;opacity: .75;filter: alpha(opacity=75);z-index:999;position:absolute;"><!-- --></div>\n'+
'    			\n'+
'    					<div id="<<this.divMessageTextWrapperId>>" style="background-color:white;border:1px solid #999999;z-index:1000;position:absolute">\n'+
'    					<div id="<<this.divMessageHeadId>>" style="text-align:center;font-weight:bold;font-size:10px;position:relative;;"><!-- --></div>\n'+
'    					<div id="<<this.divMessageTextId>>" style="position:relative;padding:3px;"><!-- --></div>\n'+
'    					</div>\n'+
'    					\n'+
'					</div>\n'+
'					\n'+
'					<div style="position:relative" id="<<this.divContentId>>"></div>\n'+
'					<div style="clear:both"><!-- --></div>\n'+
'					\n'+
'				</div>\n'+
'				\n'+
'    		]]>\n'+
'		</html>\n'+
'	</template>\n'+
'</templates>';
var Toolbox = new Object();
Toolbox.element =  {};
Toolbox.element.getPos = function (obj)
{
var curleft = 0;
var curtop = 0;
if(obj.offsetParent)
while(1)
{
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
if(!obj.offsetParent)
break;
obj = obj.offsetParent;
}
else if(obj.x)
curleft += obj.x;
else if(obj.y)
curtop += obj.y;
/*
if(obj.offsetParent)
while(1)
{
curtop += obj.offsetTop;
if(!obj.offsetParent)
break;
obj = obj.offsetParent;
}
else if(obj.y)
curtop += obj.y;
*/
return {x:curleft,y:curtop};
}
Toolbox.mouse = {};
Toolbox.mouse.getCursor = function(e) {
var tempX,tempY;
var e = e || window.event;
if ( e.clientX) {
tempX = e.clientX + document.body.scrollLeft;
tempY = e.clientY + document.body.scrollTop;
} else if (e.pageX) {
tempX = e.pageX + document.body.scrollLeft;
tempY = e.pageY + document.body.scrollTop;
}
return {x:tempX,y:tempY};
}
Toolbox.convert = {}
Toolbox.convert.formatSecs = function(sec) {
sec = Math.floor(sec);
if (sec < 0) sec = 0;
var hour = Math.floor(sec/3600);
var min = Math.floor(sec/60 );
min = ((min%60)>9 ? "" : "0")+min%60;
var sec = (((sec%60)>9) ? "" : "0")+(sec%60);
var t="";
if (hour >0)
t+=hour+":";
t+=min+":"+sec;
return t;
}
Toolbox.convert.checkLeadingZero = function(i) {
if (i<10) {
i="0" + i;
}
return i;
}
Toolbox.convert.formatDate = function(date) {
var weekdays = ["söndag","måndag","tisdag","onsdag","torsdag","fredag","lördag"];
var months = ["jan","feb","mars","april","maj","juni","juli","aug","sep","okt","nov","dec"];
var catname = date.title;
var dateparts = date.split("-");
var locstring;
if (dateparts.length == 3) {
var d = new Date(dateparts[0],(dateparts[1]-1), dateparts[2]);
var year = d.getYear();
if (year < 2000) year += 1900;
locstring = weekdays[d.getDay()] + " den " + d.getDate() + " " + months[d.getMonth()] + " " + year;
catname = locstring.toUpperCase();
}
return catname;
}
Toolbox.object = {};
Toolbox.object.getObjSize = function(obj) {
var count = 0;
for (data in obj)
count++;
return count;
}
Toolbox.object.getObjectByProperty = function(object,prop,propValue) {
var retObj;
for (i=0;i<object.length;i++) {
if (object[i][prop] == propValue)
retObj = {index:i,object:object[i]};
}
return retObj;
}
Toolbox.object.dump = function(arr,breaker,level) {
var dumped_text = "";
if(!level) level = 0;
if (!breaker)
breaker="\n";
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "&nbsp&nbsp";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' ..."+breaker;
dumped_text += Toolbox.object.dump(value,breaker,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\""+breaker;
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
Toolbox.loadScript = function(scrPath) {
return;
var head = document.getElementsByTagName('head').item(0);
var script = document.createElement('script');
script.src = scrPath+"?"+Math.round(Math.random()*10000000);
script.type = 'text/javascript';
head.appendChild(script);
}
Toolbox.getFileExt = function(file) {
var data;
data = file.split('/');
data = data[data.length-1];
var fileName = data;
data = fileName.split('.');
if (data.length > 1)
data = data[data.length-1];
else
data = "mp3-stream";
var fileExt = data;
return fileExt;
}
Toolbox.loadExternalComponent = function(comp) {
var compPath = "externalcomponents/"+comp+".js";
this.loadScript(compPath);
}
Toolbox.loadComponent = function(comp) {
var compPath = "core/"+comp+".js";
this.loadScript(compPath);
}
Toolbox.loadComponents = function(componentList,fallback,baseURL) {
this.componentList = componentList;
this.fallback = fallback;
for (i=0;i<componentList.length;i++) {
var componentPath;
if (componentList[i].internal)
componentPath = baseURL+"core/"+componentList[i].name+".js";
else
componentPath = baseURL+"externalcomponents/"+componentList[i].name+".js";
this.loadScript(componentPath);
}
Toolbox.totalComponents = componentList.length;
Toolbox.checkComponentsLoaded(componentList,fallback);
}
Toolbox.checkComponentsLoaded = function() {
if (this.componentList.length == 0) {
eval(this.fallback);
return;
}
for (i=0;i<this.componentList.length;i++) {
try {
if (eval(this.componentList[i].className))
throw "ComponentSuccessfullyInited";
}
catch (e) {
if (e == 'ComponentSuccessfullyInited') {
this.componentList.splice(i,1);
}
}
Toolbox.setLoadingText("Components",Math.round( ((Toolbox.totalComponents-this.componentList.length) / Toolbox.totalComponents)*100));
}
window.setTimeout("Toolbox.checkComponentsLoaded()",100);
}
Toolbox.componentCollection = function(_baseURL) {
var componentArray = new Array();
return {
addComponent:function(componentName,className) {
var cName = className;
if (!cName)
cName = Toolbox.string.capitalize(componentName);
componentArray[componentArray.length] = { name:componentName,className:cName,internal:true };
}
,
addExternalComponent:function(componentName,className) {
componentArray[componentArray.length] = { name:componentName,className:className,internal:false };
}
,
getComponentList:function() {
return componentArray;
}
}
}
Toolbox.loadModuleTemplates = function(moduleTemplateFiles) {
this.moduleTemplateFiles = moduleTemplateFiles;
for (i=0; i < this.moduleTemplateFiles.length; i++) {
}
}
Toolbox.checkModuleTemplatesLoaded = function() {
}
Toolbox.loadModules = function(modules,fallback,baseURL) {
this.moduleList = modules;
this.moduleFallback = fallback;
this.baseURL = baseURL;
for(var i = 0; i < this.moduleList.length; i++) {
var modName = this.moduleList[i];
this.loadModule(modName);
}
Toolbox.totalModules = this.moduleList.length;
this.checkModulesLoaded();
}
Toolbox.checkModulesLoaded = function() {
if (this.moduleList.length == 0) {
eval(this.moduleFallback);
return;
}
for (i=0;i<this.moduleList.length;i++) {
try {
if (eval(this.moduleList[i]))
throw "ModuleSuccessfullyInited";
}
catch (e) {
if (e == 'ModuleSuccessfullyInited') {
this.moduleList.splice(i,1);
}
}
}
Toolbox.setLoadingText("Modules",Math.round( ((Toolbox.totalModules-this.moduleList.length) / Toolbox.totalModules)*100));
window.setTimeout("Toolbox.checkModulesLoaded()",200);
}
Toolbox.loadModule = function(mod) {
var modPath = this.baseURL+"modules/"+mod+".js";
this.loadScript(modPath);
}
var Debug = new Object();
Debug.debugLevel = 0;
if (Debug.debugLevel > 0) {
/*var wWidth = screen.availWidth-window.outerWidth-10;
if (isNaN(wWidth)) {
wWidth = screen.availWidth-500;
}
var wLeft = screen.availWidth-wWidth;
var wTop = 0;
var wHeight = screen.availHeight;
*/
wLeft = 100;
wTop = 100;
wWidth = 400;
wHeight = 300;
Debug.win = window.open("debug.html","debug","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,left="+wLeft+",top="+wTop+",width="+wWidth+",height="+wHeight);
Debug.win.blur();
}
Debug.output = function(type,obj,method,str,breakpoint) {
Debug.win.writeDebug(type,obj,method,str,breakpoint);
}
Debug.error	= function(obj, method, str,breakpoint) { // 1
if (Debug.debugLevel >= 1)
Debug.output("error",obj,method,str,breakpoint);
}
Debug.warning = function(obj, method, str,breakpoint) { // 2
if (Debug.debugLevel >= 2)
Debug.output("warning",obj,method,str,breakpoint);
}
Debug.notice = function(obj, method, str,breakpoint) { // 3
if (Debug.debugLevel >= 3)
Debug.output("notice",obj,method,str,breakpoint);
}
var Struct = new Object();
Struct.attributes = {	host: ["name"],
folder: ["id","title","name","priority","created"],
file: ["id","name","path","size","type"],
clip:  ["id","mode","path","name","size","type"],
item: ["type"],
REF: ["HREF"],
playlist:["id"]};
Struct.render = function(parent) {
var obj = new Object();
if (Struct.attributes[parent.nodeName] != null) {
for(var a=0; a<Struct.attributes[parent.nodeName].length; a++) {
var att = Struct.attributes[parent.nodeName][a];
obj[att] = parent.getAttribute(att);
}
}
var node = parent.firstChild;
while(node != null) {
if (node.firstChild != null) {
if (node.firstChild.nodeType == 1) {
if (obj[node.nodeName] == null)
obj[node.nodeName] = new Array();
obj[node.nodeName][obj[node.nodeName].length] = Struct.render(node);
} else {
obj[node.nodeName] = node.firstChild.nodeValue;
}
} else if (node.nodeName == "folder") {
if (obj[node.nodeName] == null)
obj[node.nodeName] = new Array();
obj[node.nodeName][obj[node.nodeName].length] = Struct.render(node);
}
node = node.nextSibling;
}
return obj;
}
Toolbox.string = {};
Toolbox.string.isEmail = function(str) {
var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return filter.test(str);
}
Toolbox.string.trim = function(str) {
if (typeof str == "undefined") return;
var temp = str;
var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
var obj = /  /g;
while (temp.match(obj)) { temp = temp.replace(obj, " "); }
return temp;
}
Toolbox.string.capitalize = function(str) {
var capLetter = str.substring(0,1).toUpperCase();
var remainant = str.substring(1,str.length);
var retStr = capLetter+remainant;
return retStr;
}
Toolbox.array = {};
Toolbox.array.clone = function(arr) {
var newArray = new Array();
for (i=0;i<arr.length;i++)
newArray[newArray.length] = arr[i];
return newArray;
}
Toolbox.setLoadingText = function(text,pct) {
try {
var area = document.getElementById('playerLoadingArea');
var bar = document.getElementById('playerLoadingBar');
bar.style.width = Math.ceil( parseInt(area.style.width) * (pct/100) )+"px";
document.getElementById("playerLoadingText").innerHTML = text +": "+pct+"%";
}
catch(e) {}
}
Toolbox.removeLoadingScreen = function() {
Effect.Fade($('playerLoading'));
try {
document.getElementById("playerContainer").style.visibility = 'visible';
}catch (e){}
}
/* this needs to be moved */
/*
This work is licensed under Creative Commons GNU GPL License
http://creativecommons.org/licenses/GPL/2.0/
and based on code by Russel Lindsay www.weetbixthecat.com
Copyright Kostik Naumov www.piterpen.net
(c) 20070108
*/
Toolbox.object.sortObjectByProperty = function(arr,property,rev) {
if (!arr)
return;
var fn = function(a,b)
{
if (a[property] == parseFloat(a[property]))
a[property] = parseFloat(a[property]);
if (b[property] == parseFloat(b[property]))
b[property] = parseFloat(b[property]);
if (a[property] < b[property])
{
return (rev)? 1:-1;
} else if (a[property] > b[property])
{
return (rev)? -1:1;
} else
{
return 0;
}
}
arr.sort(fn);
return arr;
}