/*********************************************************************
* IMPORTANT NOTE:                                                    *
* This file isn't a part of the automated build and deployment.      *
* If you make changes here, please notify the person responsible for *
* deploying the application                                          *
**********************************************************************/

var gAlbumspath = "/WebGW/albums/";
var gBasepath = gAlbumspath+"triplay/";
var gResourcesPath = "/WebGW/pages/triplay/";
var gCommonPath = "/WebGW/pages/common/";
var gTemplatesPath = gCommonPath+"templates/";
var gLangParam = "lang"; // the name of the languge parameter in the URL
var gLang = "en"; // default language
var gRingtoneCreator = "/apps/download.jsp?application=T-Style";
var gFirefoxExtension = "/apps/download.jsp?application=T-Connect";

// Used in the application when u want to get the Public url.
// Like service.js#112 - getHomeUrl(), or all the URLs Object in en.js/de.js
// USING PUBLIC DOMAIN - WWW.TRIPLAY.COM
var gWWW = "www.triplay.com";

// New Domain - Email Domain.
// USING PUBLIC DOMAIN - TRIPLAY.COM
var gMAIL = "triplay.com";

// New Domain - Applicaion Domain.
// USING APPLICATION DOMAIN - USERS.TRIPLAY.COMN
var gAPP = "www.triplay.com"

var actionLocation = 'https://' + gWWW + gBasepath + 'login';
var tConnectPlugin = 'http://' + gAPP + gAlbumspath + 'plugin';
var sendPasswordActionLocation = '/login.php?token=FORGOT_PASSWORD';
var gRingtoneCreatorRegistraion = 'http://' + gAPP + gAlbumspath + 'tStyle/tStyleReg.html';
var gFirefoxExtensionRegistraion = '/registration.php?app=7'
var gFirefoxPLuginUrl = "http://" + gAPP + "/WebGW/pages/triplay/tConnectComposer.html";
// No usages in the project!
// Used to point to wap root.
// USE APP DOMAIN & /WAP - USERS.TRIPLAY.COM/WAP
var gWAP = "users.triplay-inc.com/wap";

/* system labels */
var gSystemLabels = {
	INBOX : '0',
	SENT_ITEMS : '1', 
	TRASH : '2',
	BACKPACK : '6',
	RECENTLY_RECEIVED : '9',
    GREETINGS : '23',
    PLAYLIST : null
}
/*
 * Copyright 2005 Joe Walker
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Declare an object to which we can add real functions.
 */
if (dwr == null) var dwr = {};
if (dwr.engine == null) dwr.engine = {};
if (DWREngine == null) var DWREngine = dwr.engine;

/**
 * Set an alternative error handler from the default alert box.
 * @see http://getahead.ltd.uk/dwr/browser/engine/errors
 */
dwr.engine.setErrorHandler = function(handler) {
  dwr.engine._errorHandler = handler;
};

/**
 * Set an alternative warning handler from the default alert box.
 * @see http://getahead.ltd.uk/dwr/browser/engine/errors
 */
dwr.engine.setWarningHandler = function(handler) {
  dwr.engine._warningHandler = handler;
};

/**
 * Setter for the text/html handler - what happens if a DWR request gets an HTML
 * reply rather than the expected Javascript. Often due to login timeout
 */
dwr.engine.setTextHtmlHandler = function(handler) {
  dwr.engine._textHtmlHandler = handler;
}

/**
 * Set a default timeout value for all calls. 0 (the default) turns timeouts off.
 * @see http://getahead.ltd.uk/dwr/browser/engine/errors
 */
dwr.engine.setTimeout = function(timeout) {
  dwr.engine._timeout = timeout;
};

/**
 * The Pre-Hook is called before any DWR remoting is done.
 * @see http://getahead.ltd.uk/dwr/browser/engine/hooks
 */
dwr.engine.setPreHook = function(handler) {
  dwr.engine._preHook = handler;
};

/**
 * The Post-Hook is called after any DWR remoting is done.
 * @see http://getahead.ltd.uk/dwr/browser/engine/hooks
 */
dwr.engine.setPostHook = function(handler) {
  dwr.engine._postHook = handler;
};

/**
 * Custom headers for all DWR calls
 * @see http://getahead.ltd.uk/dwr/????
 */
dwr.engine.setHeaders = function(headers) {
  dwr.engine._headers = headers;
};

/**
 * Custom parameters for all DWR calls
 * @see http://getahead.ltd.uk/dwr/????
 */
dwr.engine.setParameters = function(parameters) {
  dwr.engine._parameters = parameters;
};

/** XHR remoting type constant. See dwr.engine.set[Rpc|Poll]Type() */
dwr.engine.XMLHttpRequest = 1;

/** XHR remoting type constant. See dwr.engine.set[Rpc|Poll]Type() */
dwr.engine.IFrame = 2;

/** XHR remoting type constant. See dwr.engine.setRpcType() */
dwr.engine.ScriptTag = 3;

/**
 * Set the preferred remoting type.
 * @param newType One of dwr.engine.XMLHttpRequest or dwr.engine.IFrame or dwr.engine.ScriptTag
 * @see http://getahead.ltd.uk/dwr/browser/engine/options
 */
dwr.engine.setRpcType = function(newType) {
  if (newType != dwr.engine.XMLHttpRequest && newType != dwr.engine.IFrame && newType != dwr.engine.ScriptTag) {
    dwr.engine._handleError(null, { name:"dwr.engine.invalidRpcType", message:"RpcType must be one of dwr.engine.XMLHttpRequest or dwr.engine.IFrame or dwr.engine.ScriptTag" });
    return;
  }
  dwr.engine._rpcType = newType;
};

/**
 * Which HTTP method do we use to send results? Must be one of "GET" or "POST".
 * @see http://getahead.ltd.uk/dwr/browser/engine/options
 */
dwr.engine.setHttpMethod = function(httpMethod) {
  if (httpMethod != "GET" && httpMethod != "POST") {
    dwr.engine._handleError(null, { name:"dwr.engine.invalidHttpMethod", message:"Remoting method must be one of GET or POST" });
    return;
  }
  dwr.engine._httpMethod = httpMethod;
};

/**
 * Ensure that remote calls happen in the order in which they were sent? (Default: false)
 * @see http://getahead.ltd.uk/dwr/browser/engine/ordering
 */
dwr.engine.setOrdered = function(ordered) {
  dwr.engine._ordered = ordered;
};

/**
 * Do we ask the XHR object to be asynchronous? (Default: true)
 * @see http://getahead.ltd.uk/dwr/browser/engine/options
 */
dwr.engine.setAsync = function(async) {
  dwr.engine._async = async;
};

/**
 * Does DWR poll the server for updates? (Default: false)
 * @see http://getahead.ltd.uk/dwr/browser/engine/options
 */
dwr.engine.setActiveReverseAjax = function(activeReverseAjax) {
  dwr.engine._activeReverseAjax = activeReverseAjax;
  if (dwr.engine._activeReverseAjax) dwr.engine._poll();
};

/**
 * Does DWR us comet polling? (Default: true)
 * @see http://getahead.ltd.uk/dwr/browser/engine/options
 */
dwr.engine.setPollUsingComet = function(pollComet) {
  dwr.engine._pollComet = pollComet;
};

/**
 * Set the preferred polling type.
 * @param newPollType One of dwr.engine.XMLHttpRequest or dwr.engine.IFrame
 * @see http://getahead.ltd.uk/dwr/browser/engine/options
 */
dwr.engine.setPollType = function(newPollType) {
  if (newPollType != dwr.engine.XMLHttpRequest && newPollType != dwr.engine.IFrame) {
    dwr.engine._handleError(null, { name:"dwr.engine.invalidPollType", message:"PollType must be one of dwr.engine.XMLHttpRequest or dwr.engine.IFrame"  });
    return;
  }
  dwr.engine._pollType = newPollType;
};

/**
 * The default message handler.
 * @see http://getahead.ltd.uk/dwr/browser/engine/errors
 */
dwr.engine.defaultErrorHandler = function(message, ex) {
  dwr.engine._debug("Error: " + ex.name + ", " + ex.message, true);

  if (message == null || message == "") {
      handleDwrException(message, ex);
  } else if (message.indexOf("0x80040111") != -1) {
      dwr.engine._debug(message);  // Ignore NS_ERROR_NOT_AVAILABLE if Mozilla is being narky
      handleDwrException(message, ex);
  } else {
      handleDwrException(message, ex);
  }
};

/**
 * The default warning handler.
 * @see http://getahead.ltd.uk/dwr/browser/engine/errors
 */
dwr.engine.defaultWarningHandler = function(message, ex) {
  dwr.engine._debug(message);
};

/**
 * For reduced latency you can group several remote calls together using a batch.
 * @see http://getahead.ltd.uk/dwr/browser/engine/batch
 */
dwr.engine.beginBatch = function() {
  if (dwr.engine._batch) {
    dwr.engine._handleError(null, { name:"dwr.engine.batchBegun", message:"Batch already begun" });
    return;
  }
  dwr.engine._batch = dwr.engine._createBatch();
};

/**
 * Finished grouping a set of remote calls together. Go and execute them all.
 * @see http://getahead.ltd.uk/dwr/browser/engine/batch
 */
dwr.engine.endBatch = function(options) {
  var batch = dwr.engine._batch;
  if (batch == null) {
    dwr.engine._handleError(null, { name:"dwr.engine.batchNotBegun", message:"No batch in progress" });
    return;
  }
  dwr.engine._batch = null;
  if (batch.map.callCount == 0) return;

  // The hooks need to be merged carefully to preserve ordering
  if (options) dwr.engine._mergeBatch(batch, options);

  // In ordered mode, we don't send unless the list of sent items is empty
  if (dwr.engine._ordered && dwr.engine._batchesLength != 0) {
    dwr.engine._batchQueue[dwr.engine._batchQueue.length] = batch;
  }
  else {
    dwr.engine._sendData(batch);
  }
};

/** @deprecated */
dwr.engine.setPollMethod = function(type) { dwr.engine.setPollType(type); };
dwr.engine.setMethod = function(type) { dwr.engine.setRpcType(type); };
dwr.engine.setVerb = function(verb) { dwr.engine.setHttpMethod(verb); };

//==============================================================================
// Only private stuff below here
//==============================================================================

/** The original page id sent from the server */
dwr.engine._origScriptSessionId = "7AF0841FFB156318D23751F312BAE65D";

/** The session cookie name */
dwr.engine._sessionCookieName = "JSESSIONID"; // JSESSIONID

/** Is GET enabled for the benefit of Safari? */
// Shlomi Asaf enabled this variable for safari and made him work !!!!!
dwr.engine._allowGetForSafariButMakeForgeryEasier = true;

/** The read page id that we calculate */
dwr.engine._scriptSessionId = null;

/** The function that we use to fetch/calculate a session id */
dwr.engine._getScriptSessionId = function() {
  if (dwr.engine._scriptSessionId == null) {
    dwr.engine._scriptSessionId = dwr.engine._origScriptSessionId + Math.floor(Math.random() * 1000);
  }
  return dwr.engine._scriptSessionId;
};

/** A function to call if something fails. */
dwr.engine._errorHandler = dwr.engine.defaultErrorHandler;

/** For debugging when something unexplained happens. */
dwr.engine._warningHandler = dwr.engine.defaultWarningHandler;

/** A function to be called before requests are marshalled. Can be null. */
dwr.engine._preHook = null;

/** A function to be called after replies are received. Can be null. */
dwr.engine._postHook = null;

/** An map of the batches that we have sent and are awaiting a reply on. */
dwr.engine._batches = {};

/** A count of the number of outstanding batches. Should be == to _batches.length unless prototype has messed things up */
dwr.engine._batchesLength = 0;

/** In ordered mode, the array of batches waiting to be sent */
dwr.engine._batchQueue = [];

/** What is the default rpc type */
dwr.engine._rpcType = dwr.engine.XMLHttpRequest;

/** What is the default remoting method (ie GET or POST) */
dwr.engine._httpMethod = "POST";

/** Do we attempt to ensure that calls happen in the order in which they were sent? */
dwr.engine._ordered = false;

/** Do we make the calls async? */
dwr.engine._async = true;

/** The current batch (if we are in batch mode) */
dwr.engine._batch = null;

/** The global timeout */
dwr.engine._timeout = 0;

/** ActiveX objects to use when we want to convert an xml string into a DOM object. */
dwr.engine._DOMDocument = ["Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"];

/** The ActiveX objects to use when we want to do an XMLHttpRequest call. */
dwr.engine._XMLHTTP = ["Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];

/** Are we doing comet or polling? */
dwr.engine._activeReverseAjax = false;

/** Is there a long term poll (comet) interraction in place? */
dwr.engine._pollComet = true;

/** What is the default polling type */
dwr.engine._pollType = dwr.engine.XMLHttpRequest;
//dwr.engine._pollType = dwr.engine.IFrame;

/** The iframe that we are using to poll */
dwr.engine._pollFrame = null;

/** The xhr object that we are using to poll */
dwr.engine._pollReq = null;

/** How much data has been received into a reverse ajax document */
dwr.engine._cometProcessed = 0;

/** How many milliseconds between internal comet polls */
dwr.engine._pollCometInterval = 200;

/** Do we do a document.reload if we get a text/html reply? */
dwr.engine._textHtmlHandler = null;

/** If you wish to send custom headers with every request */
dwr.engine._headers = null;

/** If you wish to send extra custom request parameters with each request */
dwr.engine._parameters = null;

/** Undocumented interceptors - do not use */
dwr.engine._postSeperator = "\n";
dwr.engine._defaultInterceptor = function(data) {return data;}
dwr.engine._urlRewriteHandler = dwr.engine._defaultInterceptor;
dwr.engine._contentRewriteHandler = dwr.engine._defaultInterceptor;
dwr.engine._replyRewriteHandler = dwr.engine._defaultInterceptor;

/** Batch ids allow us to know which batch the server is answering */
dwr.engine._nextBatchId = 0;

/** A list of the properties that need merging from calls to a batch */
dwr.engine._propnames = [ "rpcType", "httpMethod", "async", "timeout", "errorHandler", "warningHandler", "textHtmlHandler" ];

/**
 * @private Send a request. Called by the Javascript interface stub
 * @param path part of URL after the host and before the exec bit without leading or trailing /s
 * @param scriptName The class to execute
 * @param methodName The method on said class to execute
 * @param func The callback function to which any returned data should be passed
 *       if this is null, any returned data will be ignored
 * @param vararg_params The parameters to pass to the above class
 */
//dwr.engine._execute = function(path, scriptName, methodName, vararg_params) { // ~ORR~ Removed
dwr.engine._execute = function(path, scriptName, methodName, cbfunc, cbparam, vararg_params) { // ~ORR~ Added
  var singleShot = false;
  if (dwr.engine._batch == null) {
    dwr.engine.beginBatch();
    singleShot = true;
  }
  var batch = dwr.engine._batch;
  // To make them easy to manipulate we copy the arguments into an args array
  //var args = [];// ~ORR~ Removed
  var args = vararg_params; // ~ORR~ Added
  /*for (var i = 0; i < arguments.length - 3; i++) {
    args[i] = arguments[i + 3];
  }*/ // ~ORR~ Removed
  // All the paths MUST be to the same servlet
  if (batch.path == null) {
    batch.path = path;
  }
  else {
    if (batch.path != path) {
      dwr.engine._handleError(batch, { name:"dwr.engine.multipleServlets", message:"Can't batch requests to multiple DWR Servlets." });
      return;
    }
  }
  // From the other params, work out which is the function (or object with
  // call meta-data) and which is the call parameters
  var callData;
  //var lastArg = args[args.length - 1]; // ~ORR~ Removed
  /*if (typeof lastArg == "function" || lastArg == null) callData = { callback:args.pop() };
  else callData = args.pop();*/ // ~ORR~ Removed
  callData = { callback:cbfunc, callbackparam:cbparam }; // ~ORR~ Added

  // Merge from the callData into the batch
  dwr.engine._mergeBatch(batch, callData);
  batch.handlers[batch.map.callCount] = {
    exceptionHandler:callData.exceptionHandler,
    //callback:callData.callback // ~ORR~ Removed
	callback:callData.callback, // ~ORR~ Added
    callbackparam:callData.callbackparam // ~ORR~ Added
  };

  // Copy to the map the things that need serializing
  var prefix = "c" + batch.map.callCount + "-";
  batch.map[prefix + "scriptName"] = scriptName;
  batch.map[prefix + "methodName"] = methodName;
  batch.map[prefix + "id"] = batch.map.callCount;
  for (i = 0; i < args.length; i++) {
    dwr.engine._serializeAll(batch, [], args[i], prefix + "param" + i);
  }

  // Now we have finished remembering the call, we incr the call count
  batch.map.callCount++;
  if (singleShot) dwr.engine.endBatch();
};

/** @private Poll the server to see if there is any data waiting */
dwr.engine._poll = function(overridePath) {
  if (!dwr.engine._activeReverseAjax) return;

  var batch = dwr.engine._createBatch();
  batch.map.id = 0; // TODO: Do we need this??
  batch.map.callCount = 1;
  batch.map.partialResponse = (document.all) ? "false" : "true";
  batch.isPoll = true;
  batch.rpcType = dwr.engine._pollType;
  batch.httpMethod = "POST";
  batch.async = true;
  batch.timeout = 0;
  batch.path = (overridePath) ? overridePath : dwr.engine._defaultPath;
  batch.preHooks = [];
  batch.postHooks = [];
  batch.handlers[0] = {
    callback:function(pause) {
      dwr.engine._cometBatch = null;
      setTimeout("dwr.engine._poll()", pause);
    }
  };

  // Send the data
  dwr.engine._sendData(batch);
  if (batch.map.partialResponse == "true") {
    dwr.engine._cometBatch = batch;
    dwr.engine._checkCometPoll();
  }
};

/** @private Generate a new standard batch */
dwr.engine._createBatch = function() {
  var batch = {
    map:{
      callCount:0,
      page:window.location.pathname,
      httpSessionId:dwr.engine._getJSessionId(),
      scriptSessionId:dwr.engine._getScriptSessionId()
    },
    paramCount:0, // TODO: What's this for?
    isPoll:false, headers:{}, handlers:{}, preHooks:[], postHooks:[],
    rpcType:dwr.engine._rpcType,
    httpMethod:dwr.engine._httpMethod,
    async:dwr.engine._async,
    timeout:dwr.engine._timeout,
    errorHandler:dwr.engine._errorHandler,
    warningHandler:dwr.engine._warningHandler,
    textHtmlHandler:dwr.engine._textHtmlHandler
  };
  if (dwr.engine._preHook) batch.preHooks.push(dwr.engine._preHook);
  if (dwr.engine._postHook) batch.postHooks.push(dwr.engine._postHook);
  var propname, data;
  if (dwr.engine._headers) {
    for (propname in dwr.engine._headers) {
      data = dwr.engine._headers[propname];
      if (typeof data != "function") batch.headers[propname] = "" + data;
    }
  }
  if (dwr.engine._parameters) {
    for (propname in dwr.engine._parameters) {
      data = dwr.engine._parameters[propname];
      if (typeof data != "function") batch.parameters[propname] = "" + data;
    }
  }
  return batch;
}

/** @private Take further options and merge them into */
dwr.engine._mergeBatch = function(batch, overrides) {
  var propname, data;
  for (var i = 0; i < dwr.engine._propnames.length; i++) {
    propname = dwr.engine._propnames[i];
    if (overrides[propname] != null) batch[propname] = overrides[propname];
  }
  if (overrides.preHook != null) batch.preHooks.unshift(overrides.preHook);
  if (overrides.postHook != null) batch.postHooks.push(overrides.postHook);
  if (overrides.headers) {
    for (propname in overrides.headers) {
      data = overrides[propname];
      if (typeof data != "function") batch.headers[propname] = "" + data;
    }
  }
  if (overrides.parameters) {
    for (propname in overrides.parameters) {
      data = overrides[propname];
      if (typeof data != "function") batch.map[propname] = "" + data;
    }
  }
};

/** @private What is our session id? */
dwr.engine._getJSessionId =  function() {
  var cookies = document.cookie.split(';');
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i];
    while (cookie.charAt(0) == ' ') cookie = cookie.substring(1, cookie.length);
    if (cookie.indexOf(dwr.engine._sessionCookieName + "=") == 0) {
      return cookie.substring(11, cookie.length);
    }
  }
  return "";
}

/** @private Check for reverse Ajax activity */
dwr.engine._checkCometPoll = function() {
  if (dwr.engine._pollComet) {
    // If the poll resources are still there, come back again
    //if (dwr.engine._pollFrame || dwr.engine._pollReq) {
    //  setTimeout("dwr.engine._checkCometPoll()", dwr.engine._pollCometInterval);
    //}
    try {
      dwr.engine._receivedBatch = dwr.engine._cometBatch;
      if (dwr.engine._pollFrame) {
        var text = dwr.engine._getTextFromCometIFrame();
        dwr.engine._processCometResponse(text);
      }
      else if (dwr.engine._pollReq) {
        var xhrtext = dwr.engine._pollReq.responseText;
        dwr.engine._processCometResponse(xhrtext);
      }
      dwr.engine._receivedBatch = null;
    }
    catch (ex) {
      // IE complains for no good reason for both options above. Ignore.
    }
    // If the poll resources are still there, come back again
    if (dwr.engine._pollFrame || dwr.engine._pollReq) {
      setTimeout("dwr.engine._checkCometPoll()", dwr.engine._pollCometInterval);
    }
  }
};

/** @private Extract the whole (executed an all) text from the current iframe */
dwr.engine._getTextFromCometIFrame = function() {
  var frameDocument;
  if (dwr.engine._pollFrame.contentDocument) {
    frameDocument = dwr.engine._pollFrame.contentDocument.defaultView.document;
  }
  else if (dwr.engine._pollFrame.contentWindow) {
    frameDocument = dwr.engine._pollFrame.contentWindow.document;
  }
  else {
    return "";
  }
  var bodyNodes = frameDocument.getElementsByTagName("body");
  if (bodyNodes == null || bodyNodes.length == 0) return "";
  if (bodyNodes[0] == null) return "";
  var text = bodyNodes[0].innerHTML.toString();
  // IE plays silly-pants and adds <PRE>...</PRE> for some unknown reason
  if (text.indexOf("<PRE>") == 0) text = text.substring(5, text.length - 7);
  return text;
};

/** @private Some more text might have come in, test and execute the new stuff */
dwr.engine._processCometResponse = function(response) {
  if (dwr.engine._cometProcessed != response.length) {
    if (response.length == 0) {
      dwr.engine._cometProcessed = 0;
    }
    else {
      // dwr.engine._debug("response.length=" + response.length + ", cometProcessed=" + dwr.engine._cometProcessed + ", extra chars=" + (response.length - dwr.engine._cometProcessed));
      var firstStartTag = response.indexOf("//#DWR-START#", dwr.engine._cometProcessed);
      // dwr.engine._debug("firstStartTag='" + firstStartTag + "'");
      if (firstStartTag == -1) {
        // dwr.engine._debug("Failed to find start tag when starting at " + firstStartTag + ". Dropping: " + (response.length - dwr.engine._cometProcessed) + " characters");
        dwr.engine._cometProcessed = response.length;
      }
      else {
        var lastEndTag = response.lastIndexOf("//#DWR-END#");
        // dwr.engine._debug("lastEndTag='" + lastEndTag + "'");
        if (lastEndTag != -1) {
          var exec = response.substring(firstStartTag + 13, lastEndTag);
          // Skip the end tag too for next time, remembering CR and LF
          if (response.charCodeAt(lastEndTag + 11) == 13 && response.charCodeAt(lastEndTag + 12) == 10) {
            dwr.engine._cometProcessed = lastEndTag + 13;
          }
          else {
            dwr.engine._cometProcessed = lastEndTag + 11;
          }
          dwr.engine._eval(exec);
          // dwr.engine._debug("setting _cometProcessed='" + dwr.engine._cometProcessed + "'");
        }
        // else {
        //   dwr.engine._debug("No end tag. (yet) '" + response + "'");
        // }
      }
    }
  }
};

/** @private Actually send the block of data in the batch object. */
dwr.engine._sendData = function(batch) {
  batch.map.batchId = dwr.engine._nextBatchId++;
  dwr.engine._batches[batch.map.batchId] = batch;
  dwr.engine._batchesLength++;
  batch.completed = false;

  for (var i = 0; i < batch.preHooks.length; i++) {
    batch.preHooks[i]();
  }
  batch.preHooks = null;
  // Set a timeout
  if (batch.timeout && batch.timeout != 0) {
    batch.interval = setInterval(function() { dwr.engine._abortRequest(batch); }, batch.timeout);
  }
  // Get setup for XMLHttpRequest if possible
  if (batch.rpcType == dwr.engine.XMLHttpRequest) {
    if (window.XMLHttpRequest) {
      batch.req = new XMLHttpRequest();
    }
    // IE5 for the mac claims to support window.ActiveXObject, but throws an error when it's used
    else if (window.ActiveXObject && !(navigator.userAgent.indexOf("Mac") >= 0 && navigator.userAgent.indexOf("MSIE") >= 0)) {
      batch.req = dwr.engine._newActiveXObject(dwr.engine._XMLHTTP);
    }
  }

  var prop, request;
  if (batch.req) {
    // Proceed using XMLHttpRequest
    if (batch.async) {
      batch.req.onreadystatechange = function() { dwr.engine._stateChange(batch); };
    }
    // If we're polling, record this for monitoring
    if (batch.isPoll) dwr.engine._pollReq = batch.req;
    // Workaround for Safari 1.x POST bug
    var indexSafari = navigator.userAgent.indexOf("Safari/");
    if (indexSafari >= 0) {
      if (dwr.engine._allowGetForSafariButMakeForgeryEasier)
      {
        var version = navigator.userAgent.substring(indexSafari + 7);
        if (parseInt(version, 10) < 400) batch.httpMethod = "GET";
      }
      else {
        dwr.engine._handleWarning(batch, { name:"dwr.engine.oldSafari", message:"Safari GET support disabled. See http://getahead.ltd.uk/dwr/server/servlet and allowGetForSafariButMakeForgeryEasier." });
      }
    }
    batch.mode = batch.isPoll ? dwr.engine._ModePlainPoll : dwr.engine._ModePlainCall;
    request = dwr.engine._constructRequest(batch);
    try {
      batch.req.open(batch.httpMethod, request.url, batch.async);
      try {
        for (prop in batch.headers) {
          var value = batch.headers[prop];
          if (typeof value == "string") batch.req.setRequestHeader(prop, value);
        }
        if (!batch.headers["Content-Type"]) batch.req.setRequestHeader("Content-Type", "text/plain");
      }
      catch (ex) {
        dwr.engine._handleWarning(batch, ex);
      }
      batch.req.send(request.body);
      if (!batch.async) dwr.engine._stateChange(batch);
    }
    catch (ex) {
      dwr.engine._handleError(batch, ex);
    }
  }
  else if (batch.rpcType != dwr.engine.ScriptTag) {
    var idname = "dwr-if-" + batch.map["c0-id"];
    // Proceed using iframe
    batch.div = document.createElement("div");
    batch.div.innerHTML = "<iframe src='javascript:void(0)' frameborder='0' width='0' height='0' id='" + idname + "' name='" + idname + "'></iframe>";
    document.body.appendChild(batch.div);
    batch.iframe = document.getElementById(idname);
    batch.iframe.setAttribute("style", "width:0px; height:0px; border:0px;");
    batch.iframe.batch = batch;
    batch.mode = batch.isPoll ? dwr.engine._ModeHtmlPoll : dwr.engine._ModeHtmlCall;
    if (batch.isPoll) {
      // Settings that vary if we are polling
      dwr.engine._pollFrame = batch.iframe;
      dwr.engine._cometProcessed = 0;
    }
    request = dwr.engine._constructRequest(batch);
    if (batch.httpMethod == "GET") {
      batch.iframe.setAttribute("src", request.url);
      document.body.appendChild(batch.iframe);
    }
    else {
      batch.form = document.createElement("form");
      batch.form.setAttribute("id", "dwr-form");
      batch.form.setAttribute("action", request.url);
      batch.form.setAttribute("target", idname);
      batch.form.target = idname;
      batch.form.setAttribute("method", batch.httpMethod);
      for (prop in batch.map) {
        var value = batch.map[prop];
        if (typeof value != "function") {
          var formInput = document.createElement("input");
          formInput.setAttribute("type", "hidden");
          formInput.setAttribute("name", prop);
          formInput.setAttribute("value", value);
          batch.form.appendChild(formInput);
        }
      }
      document.body.appendChild(batch.form);
      batch.form.submit();
    }
  }
  else {
    batch.httpMethod = "GET"; // There's no such thing as ScriptTag using POST
    batch.mode = batch.isPoll ? dwr.engine._ModePlainPoll : dwr.engine._ModePlainCall;
    request = dwr.engine._constructRequest(batch);
    batch.script = document.createElement("script");
    batch.script.id = "dwr-st-" + batch.map["c0-id"];
    batch.script.src = request.url;
    document.body.appendChild(batch.script);
  }
};

dwr.engine._ModePlainCall = "/call/plaincall/";
dwr.engine._ModeHtmlCall = "/call/htmlcall/";
dwr.engine._ModePlainPoll = "/call/plainpoll/";
dwr.engine._ModeHtmlPoll = "/call/htmlpoll/";

/** @private Work out what the URL should look like */
dwr.engine._constructRequest = function(batch) {
  // A quick string to help people that use web log analysers
  var request = { url:batch.path + batch.mode, body:null };
  if (batch.isPoll == true) {
    request.url += "ReverseAjax.dwr";
  }
  else if (batch.map.callCount == 1) {
    request.url += batch.map["c0-scriptName"] + "." + batch.map["c0-methodName"] + ".dwr";
  }
  else {
    request.url += "Multiple." + batch.map.callCount + ".dwr";
  }
  // Play nice with url re-writing
  var sessionMatch = location.href.match(/jsessionid=(\w+)/);
  if (sessionMatch != null) {
    request.url += ";jsessionid=" + sessionMatch[1];
  }

  var prop;
  if (batch.httpMethod == "GET") {
    // Some browsers (Opera/Safari2) seem to fail to convert the callCount value
    // to a string in the loop below so we do it manually here.
    batch.map.callCount = "" + batch.map.callCount;
    request.url += "?";
    for (prop in batch.map) {
      if (typeof batch.map[prop] != "function") {
        request.url += encodeURIComponent(prop) + "=" + encodeURIComponent(batch.map[prop]) + "&";
      }
    }
    request.url = request.url.substring(0, request.url.length - 1);
  }
  else {
    // PERFORMANCE: for iframe mode this is thrown away.
    request.body = "";
    for (prop in batch.map) {
      if (typeof batch.map[prop] != "function") {
        request.body += prop + "=" + batch.map[prop] + dwr.engine._postSeperator;
      }
    }
    request.body = dwr.engine._contentRewriteHandler(request.body);
  }
  request.url = dwr.engine._urlRewriteHandler(request.url);
  return request;
};

/** @private Called by XMLHttpRequest to indicate that something has happened */
dwr.engine._stateChange = function(batch) {
  var toEval;

  if (batch.completed) {
    dwr.engine._debug("Error: _stateChange() with batch.completed");
    return;
  }

  try {
    if (batch.req.readyState != 4) return;
  }
  catch (ex) {
    dwr.engine._handleWarning(batch, ex);
    // It's broken - clear up and forget this call
    dwr.engine._clearUp(batch);
    return;
  }

  try {
    var reply = batch.req.responseText;
    reply = dwr.engine._replyRewriteHandler(reply);
    var status = batch.req.status; // causes Mozilla to except on page moves

    if (reply == null || reply == "") {
      dwr.engine._handleWarning(batch, { name:"dwr.engine.missingData", message:"No data received from server" });
    }
    else if (status != 200) {
      dwr.engine._handleError(batch, { name:"dwr.engine.http." + status, message:reply });
    }
    else {
      var contentType = batch.req.getResponseHeader("Content-Type");
      if (!contentType.match(/^text\/plain/) && !contentType.match(/^text\/javascript/)) {
        if (contentType.match(/^text\/html/) && typeof batch.textHtmlHandler == "function") {
          batch.textHtmlHandler();
        }
        else {
          dwr.engine._handleWarning(batch, { name:"dwr.engine.invalidMimeType", message:"Invalid content type: '" + contentType + "'" });
        }
      }
      else {
        // Comet replies might have already partially executed
        if (batch.req == dwr.engine._pollReq && batch.map.partialResponse == "true") {
          dwr.engine._receivedBatch = batch;
          dwr.engine._processCometResponse(reply);
          dwr.engine._receivedBatch = null;
        }
        else {
          if (reply.search("//#DWR") == -1) {
            dwr.engine._handleWarning(batch, { name:"dwr.engine.invalidReply", message:"Invalid reply from server" });
          }
          else {
            toEval = reply;
          }
        }
      }
    }
  }
  catch (ex) {
    dwr.engine._handleWarning(batch, ex);
  }

  dwr.engine._callPostHooks(batch);

  // Outside of the try/catch so errors propogate normally:
  dwr.engine._receivedBatch = batch;
  dwr.engine._eval(toEval);
  dwr.engine._receivedBatch = null;

  dwr.engine._clearUp(batch);
};

/** @private Called by the server: Execute a callback */
dwr.engine._remoteHandleCallback = function(batchId, callId, reply) {
  var batch = dwr.engine._batches[batchId];
  if (batch == null) {
    dwr.engine._debug("Warning: batch == null in remoteHandleCallback for batchId=" + batchId, true);
    return;
  }
  // Error handlers inside here indicate an error that is nothing to do
  // with DWR so we handle them differently.
  try {
    var handlers = batch.handlers[callId];
    if (!handlers) {
      dwr.engine._debug("Warning: Missing handlers. callId=" + callId, true);
    }
    //else if (typeof handlers.callback == "function") handlers.callback(reply); // ~ORR~ Removed
	else if (typeof handlers.callback == "function") handlers.callback(handlers.callbackparam, reply); // ~ORR~ Added
  }
  catch (ex) {
    dwr.engine._handleError(batch, ex);
  }
};

/** @private Called by the server: Handle an exception for a call */
dwr.engine._remoteHandleException = function(batchId, callId, ex) {
  var batch = dwr.engine._batches[batchId];
  if (batch == null) { dwr.engine._debug("Warning: null batch in remoteHandleException", true); return; }
  var handlers = batch.handlers[callId];
  if (handlers == null) { dwr.engine._debug("Warning: null handlers in remoteHandleException", true); return; }
  if (ex.message == undefined) ex.message = "";
  if (typeof handlers.exceptionHandler == "function") handlers.exceptionHandler(ex.message, ex);
  else if (typeof batch.errorHandler == "function") batch.errorHandler(ex.message, ex);
};

/** @private Called by the server: The whole batch is broken */
dwr.engine._remoteHandleBatchException = function(ex, batchId) {
  var searchBatch = (dwr.engine._receivedBatch == null && batchId != null);
  if (searchBatch) {
    dwr.engine._receivedBatch = dwr.engine._batches[batchId];
  }
  if (ex.message == undefined) ex.message = "";
  dwr.engine._handleError(dwr.engine._receivedBatch, ex);
  if (searchBatch) {
    dwr.engine._receivedBatch = null;
    dwr.engine._clearUp(dwr.engine._batches[batchId]);
  }
};

/** @private Called by the server: Reverse ajax should not be used */
dwr.engine._remotePollCometDisabled = function(ex, batchId) {
  dwr.engine.setActiveReverseAjax(false);
  var searchBatch = (dwr.engine._receivedBatch == null && batchId != null);
  if (searchBatch) {
    dwr.engine._receivedBatch = dwr.engine._batches[batchId];
  }
  if (ex.message == undefined) ex.message = "";
  dwr.engine._handleError(dwr.engine._receivedBatch, ex);
  if (searchBatch) {
    dwr.engine._receivedBatch = null;
    dwr.engine._clearUp(dwr.engine._batches[batchId]);
  }
};

/** @private Called by the server: An IFrame reply is about to start */
dwr.engine._remoteBeginIFrameResponse = function(element, batchId) {
  dwr.engine._receivedBatch = element.batch;
  element.batch = null;
  dwr.engine._callPostHooks(batch);
};

/** @private Called by the server: An IFrame reply is just completing */
dwr.engine._remoteEndIFrameResponse = function(batchId) {
  dwr.engine._clearUp(dwr.engine._receivedBatch);
  dwr.engine._receivedBatch = null;
};

/** @private This is a hack to make the context be this window */
dwr.engine._eval = function(script) {
  if (script == null) { return null; }
  if (script == "") { dwr.engine._debug("Warning: blank script", true); return null; }
  var debug = script;
  debug = debug.replace(/\/\/#DWR-START#\r\n/g, "");
  debug = debug.replace(/\/\/#DWR-END#\r\n/g, "");
  debug = debug.replace(/\r/g, "");
  debug = debug.replace(/\n/g, " ");
  dwr.engine._debug("Exec: [" + debug + "]");
  return eval(script);
};

/** @private Called as a result of a request timeout */
dwr.engine._abortRequest = function(batch) {
  if (batch && !batch.completed) {
    clearInterval(batch.interval);
    dwr.engine._clearUp(batch);
    if (batch.req) batch.req.abort();
    dwr.engine._handleError(batch, { name:"dwr.engine.timeout", message:"Timeout" });
  }
};

/** @private call all the post hooks for a batch */
dwr.engine._callPostHooks = function(batch) {
  if (batch.postHooks) {
    for (var i = 0; i < batch.postHooks.length; i++) {
      batch.postHooks[i]();
    }
    batch.postHooks = null;
  }
}

/** @private A call has finished by whatever means and we need to shut it all down. */
dwr.engine._clearUp = function(batch) {
  if (!batch) { dwr.engine._debug("Warning: null batch in dwr.engine._clearUp()", true); return; }
  if (batch.completed == "true") { dwr.engine._debug("Warning: Double complete", true); return; }

  // IFrame tidyup
  if (batch.div) batch.div.parentNode.removeChild(batch.div);
  if (batch.iframe) {
    // If this is a poll frame then stop comet polling
    if (batch.iframe == dwr.engine._pollFrame) dwr.engine._pollFrame = null;
    batch.iframe.parentNode.removeChild(batch.iframe);
  }
  if (batch.form) batch.form.parentNode.removeChild(batch.form);

  // XHR tidyup: avoid IE handles increase
  if (batch.req) {
    // If this is a poll frame then stop comet polling
    if (batch.req == dwr.engine._pollReq) dwr.engine._pollReq = null;
    delete batch.req;
  }

  if (batch.map && batch.map.batchId) {
    delete dwr.engine._batches[batch.map.batchId];
    dwr.engine._batchesLength--;
  }

  batch.completed = true;

  // If there is anything on the queue waiting to go out, then send it.
  // We don't need to check for ordered mode, here because when ordered mode
  // gets turned off, we still process *waiting* batches in an ordered way.
  if (dwr.engine._batchQueue.length != 0) {
    var sendbatch = dwr.engine._batchQueue.shift();
    dwr.engine._sendData(sendbatch);
  }
};

/** @private Generic error handling routing to save having null checks everywhere */
dwr.engine._handleError = function(batch, ex) {
  if (typeof ex == "string") ex = { name:"unknown", message:ex };
  if (ex.message == null) ex.message = "";
  if (ex.name == null) ex.name = "unknown";
  if (batch && typeof batch.errorHandler == "function") batch.errorHandler(ex.message, ex);
  else if (dwr.engine._errorHandler) dwr.engine._errorHandler(ex.message, ex);
  dwr.engine._clearUp(batch);
};

/** @private Generic error handling routing to save having null checks everywhere */
dwr.engine._handleWarning = function(batch, ex) {
  if (typeof ex == "string") ex = { name:"unknown", message:ex };
  if (ex.message == null) ex.message = "";
  if (ex.name == null) ex.name = "unknown";
  if (batch && typeof batch.warningHandler == "function") batch.warningHandler(ex.message, ex);
  else if (dwr.engine._warningHandler) dwr.engine._warningHandler(ex.message, ex);
  dwr.engine._clearUp(batch);
};

/**
 * @private Marshall a data item
 * @param batch A map of variables to how they have been marshalled
 * @param referto An array of already marshalled variables to prevent recurrsion
 * @param data The data to be marshalled
 * @param name The name of the data being marshalled
 */
dwr.engine._serializeAll = function(batch, referto, data, name) {
  if (data == null) {
    batch.map[name] = "null:null";
    return;
  }

  switch (typeof data) {
  case "boolean":
    batch.map[name] = "boolean:" + data;
    break;
  case "number":
    batch.map[name] = "number:" + data;
    break;
  case "string":
    batch.map[name] = "string:" + encodeURIComponent(data);
    break;
  case "object":
    if (data instanceof String) batch.map[name] = "String:" + encodeURIComponent(data);
    else if (data instanceof Boolean) batch.map[name] = "Boolean:" + data;
    else if (data instanceof Number) batch.map[name] = "Number:" + data;
    else if (data instanceof Date) batch.map[name] = "Date:" + data.getTime();
    else if (data instanceof Array) batch.map[name] = dwr.engine._serializeArray(batch, referto, data, name);
    else batch.map[name] = dwr.engine._serializeObject(batch, referto, data, name);
    break;
  case "function":
    // We just ignore functions.
    break;
  default:
    dwr.engine._handleWarning(null, { name:"dwr.engine.unexpectedType", message:"Unexpected type: " + typeof data + ", attempting default converter." });
    batch.map[name] = "default:" + data;
    break;
  }
};

/** @private Have we already converted this object? */
dwr.engine._lookup = function(referto, data, name) {
  var lookup;
  // Can't use a map: http://getahead.ltd.uk/ajax/javascript-gotchas
  for (var i = 0; i < referto.length; i++) {
    if (referto[i].data == data) {
      lookup = referto[i];
      break;
    }
  }
  if (lookup) return "reference:" + lookup.name;
  referto.push({ data:data, name:name });
  return null;
};

/** @private Marshall an object */
dwr.engine._serializeObject = function(batch, referto, data, name) {
  var ref = dwr.engine._lookup(referto, data, name);
  if (ref) return ref;

  // This check for an HTML is not complete, but is there a better way?
  // Maybe we should add: data.hasChildNodes typeof "function" == true
  if (data.nodeName && data.nodeType) {
    return dwr.engine._serializeXml(batch, referto, data, name);
  }

  // treat objects as an associative arrays
  var reply = "Object_" + dwr.engine._getObjectClassName(data) + ":{";
  var element;
  for (element in data) {
    batch.paramCount++;
    var childName = "c" + dwr.engine._batch.map.callCount + "-e" + batch.paramCount;
    dwr.engine._serializeAll(batch, referto, data[element], childName);

    reply += encodeURIComponent(element) + ":reference:" + childName + ", ";
  }

  if (reply.substring(reply.length - 2) == ", ") {
    reply = reply.substring(0, reply.length - 2);
  }
  reply += "}";

  return reply;
};

/** @private Returns the classname of supplied argument obj */
dwr.engine._errorClasses = { "Error":Error, "EvalError":EvalError, "RangeError":RangeError, "ReferenceError":ReferenceError, "SyntaxError":SyntaxError, "TypeError":TypeError, "URIError":URIError };
dwr.engine._getObjectClassName = function(obj) {
  // Try to find the classname by stringifying the object's constructor
  // and extract <class> from "function <class>".
  if (obj && obj.constructor && obj.constructor.toString)
  {
    var str = obj.constructor.toString();
    var regexpmatch = str.match(/function\s+(\w+)/);
    if (regexpmatch && regexpmatch.length == 2) {
      return regexpmatch[1];
    }
  }

  // Now manually test against the core Error classes, as these in some 
  // browsers successfully match to the wrong class in the 
  // Object.toString() test we will do later
  if (obj && obj.constructor) {
	for (var errorname in dwr.engine._errorClasses) {
      if (obj.constructor == dwr.engine._errorClasses[errorname]) return errorname;
    }
  }

  // Try to find the classname by calling Object.toString() on the object
  // and extracting <class> from "[object <class>]"
  if (obj) {
    var str = Object.prototype.toString.call(obj);
    var regexpmatch = str.match(/\[object\s+(\w+)/);
    if (regexpmatch && regexpmatch.length==2) {
      return regexpmatch[1];
    }
  }

  // Supplied argument was probably not an object, but what is better?
  return "Object";
};

/** @private Marshall an object */
dwr.engine._serializeXml = function(batch, referto, data, name) {
  var ref = dwr.engine._lookup(referto, data, name);
  if (ref) return ref;

  var output;
  if (window.XMLSerializer) output = new XMLSerializer().serializeToString(data);
  else if (data.toXml) output = data.toXml;
  else output = data.innerHTML;

  return "XML:" + encodeURIComponent(output);
};

/** @private Marshall an array */
dwr.engine._serializeArray = function(batch, referto, data, name) {
  var ref = dwr.engine._lookup(referto, data, name);
  if (ref) return ref;

  var reply = "Array:[";
  for (var i = 0; i < data.length; i++) {
    if (i != 0) reply += ",";
    batch.paramCount++;
    var childName = "c" + dwr.engine._batch.map.callCount + "-e" + batch.paramCount;
    dwr.engine._serializeAll(batch, referto, data[i], childName);
    reply += "reference:";
    reply += childName;
  }
  reply += "]";

  return reply;
};

/** @private Convert an XML string into a DOM object. */
dwr.engine._unserializeDocument = function(xml) {
  var dom;
  if (window.DOMParser) {
    var parser = new DOMParser();
    dom = parser.parseFromString(xml, "text/xml");
    if (!dom.documentElement || dom.documentElement.tagName == "parsererror") {
      var message = dom.documentElement.firstChild.data;
      message += "\n" + dom.documentElement.firstChild.nextSibling.firstChild.data;
      throw message;
    }
    return dom;
  }
  else if (window.ActiveXObject) {
    dom = dwr.engine._newActiveXObject(dwr.engine._DOMDocument);
    dom.loadXML(xml); // What happens on parse fail with IE?
    return dom;
  }
  else {
    var div = document.createElement("div");
    div.innerHTML = xml;
    return div;
  }
};

/** @param axarray An array of strings to attempt to create ActiveX objects from */
dwr.engine._newActiveXObject = function(axarray) {
  var returnValue;  
  for (var i = 0; i < axarray.length; i++) {
    try {
      returnValue = new ActiveXObject(axarray[i]);
      break;
    }
    catch (ex) { /* ignore */ }
  }
  return returnValue;
};


/** Used internally when some message needs to get to the programmer */
dwr.engine._debug = function(message, stacktrace) {
  if (window.console) {
    if (stacktrace && window.console.trace) window.console.trace();
    window.console.log(message);
  }
  else if (window.opera && window.opera.postError) {
    window.opera.postError(message);
  }
  // else if (window.navigator.product == "Gecko") {
  //  window.dump(message + "\n");
  // }
  else {
    var debug = document.getElementById("dwr-debug");
    if (debug) {
      var contents = message + "<br/>" + debug.innerHTML;
      if (contents.length > 2048) contents = contents.substring(0, 2048);
      debug.innerHTML = contents;
    }
  }
};


if (dwr == null) var dwr = {};
if (dwr.engine == null) dwr.engine = {};
if (DWREngine == null) var DWREngine = dwr.engine;

dwr.engine._defaultPath = '/WebGW/albums';

var CM = {
	path: '/WebGW/albums',
	app: 'WebGW',
	simulated: false
}

/**
 * === Client Manager Interface ===
 */
CM.methods = {
	getUserCommunicationAddressTOs$AP :					['WebGWContactManager', 'getUserCommunicationAddressTOs', 'updateUserCommunicationAddresses'],
	getUserContactsTOs$AP :								['WebGWContactManager', 'getUserContactTOs', 'updateUserContactTOs'],
    getSubscriptionPackageData :                        ['WebGWUserManager', 'getSubscriptionPackageData', 'updateSubscriptionPackageData'],
    getPublicUserProfile$AP :							['WebGWContactManager', 'getPublicUserProfile', 'setPublicUserProfile'],
	contactUpdateRequest$add :							['WebGWContactManager', 'contactUpdateRequest', 'doAddContact'],
	contactUpdateRequest$update :						['WebGWContactManager', 'contactUpdateRequest', 'doUpdateContact'],
	contactUpdateRequest$delete :						['WebGWContactManager', 'contactUpdateRequest', 'doDeleteContacts'],
	acceptContactPrivilegeRequest$AP :					['WebGWContactManager', 'acceptContact', 'null'],
	blockContactPrivilegeRequest$AP :					['WebGWContactManager', 'blockContact', 'null'],
	updateCabinetDigitHeaders$updateDigitCaption :		['WebGWDigitManager', 'updateCabinetDigitHeaders', 'null'],
	sendDigit$AP :										['WebGWDigitManager', 'sendDigitRequest', 'doSendMessage'],
	forwardDigit$AP :									['WebGWDigitManager', 'forwardDigit', 'doSendMessage'],
	replyDigit$AP :										['WebGWDigitManager', 'reply', 'doSendMessage'],
	shareLink$AP :										['WebGWDigitManager', 'shareLinkRequest', 'doSendMessage'],
	forwardDigit$doSendToMyPhone :						['WebGWDigitManager', 'forwardDigit', 'doSendToMobile'],
	forwardDigit$doSendMusicToMyPhone :					['WebGWDigitManager', 'forwardDigit', 'doSendMusicToMyPhone'],
	forwardFromBackPack$AP :							['WebGWDigitManager', 'forwardDigitFromBackPack', 'doSendMessage'],
//	getMappingDigitsToLabels$AP :						['WebGWDigitManager', 'getMappingDigitsToLabels', 'setMappingDigitsToLabels'],
    moveDigits$AP :										['WebGWDigitManager', 'moveDigits', 'doUpdateCabinetDigitHeaders'],
    deleteDigitsFromAlbum$AP :							['WebGWDigitManager', 'deleteDigitsFromAlbum', 'doUpdateCabinetDigitHeaders'],
	updateCabinetDigitHeaders$AP :						['WebGWDigitManager', 'updateCabinetDigitHeaders', 'doUpdateCabinetDigitHeaders'],
	updateCabinetDigitHeaders$emptyTrash :				['WebGWDigitManager', 'updateCabinetDigitHeaders', 'doEmptyTrash'],
	updateCabinetDigitHeaders$deleteMessages :			['WebGWDigitManager', 'updateCabinetDigitHeaders', 'doDeleteMessages'],
	updateCabinetDigitHeaders$undoMoveToTrash :			['WebGWDigitManager', 'updateCabinetDigitHeaders', 'doUndoMoveToTrash'],
	copyDigitsFromInboxToBackpack$AP :					['WebGWDigitManager', 'copyDigitsFromInboxToBackpack', 'doUpdateCabinetDigitHeaders'],
	updateCabinetDigitHeaders$postRotateDigit :			['WebGWDigitManager', 'updateCabinetDigitHeaders', 'postRotateDigit'],
	cropImage$AP :										['WebGWImageEditingManager', 'cropImage', 'doCropImage'],
	removeLabel$AP :									['WebGWLabelManager', 'removeLabel', 'updateAlbumListAfterRemoveAlbum'],
	getUserAlbums$renderAlbumsListPage :				['WebGWLabelManager', 'getUserAlbums', 'renderAlbumsListPage'],
	getUserAlbums$FirstLoadUserAlbums :					['WebGWLabelManager', 'getUserAlbums', 'getFirstLoadUserAlbums'],
/*	getUserAlbums$FirstLoadAllDigits :					['WebGWLabelManager', 'getUserAlbums', 'getFirstLoadAllDigits'],*/
	getUserAlbums$FirstLoadDigits :						['WebGWLabelManager', 'getUserAlbums', 'getFirstLoadDigits'],
	getUserAlbums$refreshAlbumDigitsList :				['WebGWLabelManager', 'getUserAlbums', 'refreshAlbumDigitsList'],
	getUserAlbums$renderAlbumList :						['WebGWLabelManager', 'getUserAlbums', 'renderAlbumList'],
	getUserAlbums$setAlbumCover :						['WebGWLabelManager', 'getUserAlbums', 'doSetAlbumCover'],
	getPublicAlbums$renderPublicAlbumsList :			['WebGWLabelManager', 'getPublicAlbums', 'renderPublicAlbumsList'],
	getPublicAlbums$FirstLoadPublicAlbums :				['WebGWLabelManager', 'getPublicAlbums', 'getFirstLoadPublicAlbums'],
/*	getPublicAlbums$FirstLoadAllPublicDigits :			['WebGWLabelManager', 'getPublicAlbums', 'getFirstLoadAllPublicDigits'],*/
	getPublicAlbums$FirstLoadPublicDigits :				['WebGWLabelManager', 'getPublicAlbums', 'getFirstLoadPublicDigits'],
	getPublicAlbums$handlePublicAlbumsUrl :				['WebGWLabelManager', 'getPublicAlbums', 'handlePublicAlbumsUrl'],
	getPublicAlbums$extractAlbumTO :					['WebGWLabelManager', 'getPublicAlbums' , 'extractAlbumTO'],
	getPublicAlbums$amExtractAlbumTO :					['WebGWLabelManager', 'getPublicAlbums' , 'amExtractAlbumTO'],
    getPublicAlbums$getPublicAlbumAsAttachment:         ['WebGWLabelManager', 'getPublicAlbums' , 'getPublicAlbumAsAttachment'],
    createNewLabel$updateAlbumListAfterAdd :			['WebGWLabelManager', 'createNewLabel', 'updateAlbumListAfterAdd'],
	createNewLabel$updateAlbumList_and_moveTo :			['WebGWLabelManager', 'createNewLabel', 'updateAlbumList_and_moveTo'],
/*	createNewLabel$updateAlbumList_and_moveTo_single :	['WebGWLabelManager', 'createNewLabel', 'updateAlbumList_and_moveTo_single'],*/
/*	createNewLabel$updateAlbumList_and_open_upload :	['WebGWLabelManager', 'createNewLabel', 'updateAlbumList_and_open_upload'],*/
	updateLabel$AP :									['WebGWLabelManager', 'updateLabel', 'updateAlbumList'],
	updateLabel$setAlbumCover :							['WebGWLabelManager', 'updateLabel', 'updateAlbumsListAndSetAlbumCover'],
	getTriplayLoginResponse$AP :						['WebGWSessionManager', 'getTriplayLoginResponse', 'updateLoginResponse'],
	login$AP :											['WebGWSessionManager', 'login', 'doLogin'],
	logout$AP :											['WebGWSessionManager', 'logout', 'logout'],
	getPublicAlbumUrlInfo$AP :							['WebGWSessionManager', 'getPublicAlbumUrlInfo', 'setPublicAlbumUrlInfo'],
	setRedirectURL$AP :									['WebGWSessionManager', 'setRedirectURL', 'doSetRedirectURL'],
	setPresenceState$AP :								['WebGWSettingsManager', 'setPresenceState', 'callbackPhoneState'],
	setPresenceState$logout :							['WebGWSettingsManager', 'setPresenceState', 'logout'],
	setPresenceStateFromSettings$AP :					['WebGWSettingsManager', 'setPresenceState', 'callbackFromSettingsPhoneState'],
	getUserStorageInfo$AP :								['WebGWStorageManager', 'getUserStorageInfo', 'updateUserStorageInfo'],
	sendApplicationToMobile$AP :						['WebGWUserManager', 'sendApplicationToMobile', 'doSendApplicationToMobile'],
	isUserNameExist$AP :								['WebGWUserManager', 'isUserNameExist', 'doUserNameExist'],
	isNumberRegistered$AP :								['WebGWUserManager', 'isNumberRegistered', 'doNumberRegistered'],
	isNumberRegistered$addContact :						['WebGWUserManager', 'isNumberRegistered', 'addContact'],
	sendRegistrationCode$AP :							['WebGWUserManager', 'sendRegistrationCode', 'null'],
	triplayRegistation$AP :								['WebGWUserManager', 'triplayRegistation', 'doRegister'],
	SendForPassword$AP :								['WebGWUserManager', 'forgotMyPassword', 'doSendPassword'],
	isRegistrationCodeValid$AP :						['WebGWUserManager', 'isRegistrationCodeValid', 'doCheckActivationCode'],
	reportBlockContent$AP :								['WebGWContentManager', 'reportBlockContent', 'doReportBlockContent'],
	getClientResponse$AP :								['WebGWNotificationManager', 'getClientResponse', 'notificationsHandler'],
	getClientPublicResponse$AP :						['WebGWNotificationManager', 'getClientPublicResponse', 'doKeepAlive'],
	getConversation$doOpenContab :						['WebGWDigitManager', 'getConversation', 'gDigitsCacheManager.cacheDigits', 'doOpenContab'],
	getDigits$doOpenContab :							['WebGWDigitManager', 'getDigits', 'gDigitsCacheManager.cacheDigits', 'doOpenContab'],
	getConversation$renderActivityMonitor :				['WebGWDigitManager', 'getConversation', 'gDigitsCacheManager.cacheDigits', 'renderActivityMonitor'],

	/* getDigits labels */
	cacheDigits$renderActivityMonitor : 				['WebGWDigitManager', 'getConversation', 'gDigitsCacheManager.cacheDigits', 'renderActivityMonitor'],
	cacheDigits$renderContab : 							['WebGWDigitManager', 'getConversation', 'gDigitsCacheManager.cacheDigits', 'renderContab'],
	cacheDigits$renderTrashContab : 					['WebGWDigitManager', 'getDigits', 'gDigitsCacheManager.cacheDigits', 'renderContab'],
	cacheDigits$renderAlbumPage : 						['WebGWDigitManager', 'getDigits', 'gDigitsCacheManager.cacheDigits', 'renderAlbumPage'],
	cacheDigits$showMusicAlbum : 						['WebGWDigitManager', 'getDigits', 'gDigitsCacheManager.cacheDigits', 'showMusicAlbum'],
	cacheDigits$setPrevThumb : 							['WebGWDigitManager', 'getDigits', 'gDigitsCacheManager.cacheDigits', 'setPrevThumb'],
	cacheDigits$setNextThumb : 							['WebGWDigitManager', 'getDigits', 'gDigitsCacheManager.cacheDigits', 'setNextThumb'],
	cacheDigits$getFirstLoadDigit : 					['WebGWDigitManager', 'getDigits', 'gDigitsCacheManager.cacheDigits', 'getFirstLoadDigit'],
	cacheDigits$getFirstLoadPublicDigit : 				['WebGWDigitManager', 'getPublicDigits', 'gDigitsCacheManager.cacheDigits', 'getFirstLoadPublicDigit'],
	cacheDigits$renderPublicDigitPage : 				['WebGWDigitManager', 'getPublicDigits', 'gDigitsCacheManager.cacheDigits', 'renderPublicDigitPage'],
	cacheDigits$renderPublicAlbumPage : 				['WebGWDigitManager', 'getPublicDigits', 'gDigitsCacheManager.cacheDigits', 'renderPublicAlbumPage'],
	cacheDigits$renderMusicPreview : 					['WebGWDigitManager', 'getDigits', 'gDigitsCacheManager.cacheDigits', 'renderMusicPreview'],
	cacheDigits$renderRecentlyRecived :					['WebGWDigitManager', 'getDigits', 'gDigitsCacheManager.cacheDigits', 'renderRecentlyRecived'],
    cacheDigits$renderGreetings :					    ['WebGWDigitManager', 'getDigits', 'gDigitsCacheManager.cacheDigits', 'renderGreetings'],
    cacheDigits$doOpenMessage :							['WebGWDigitManager', 'getConversation', 'gDigitsCacheManager.cacheDigits', 'doOpenMessage'],

	setMessageReadFlag$AP :								['WebGWDigitManager', 'updateMessageReadFlag', 'null'],

	getDigitAttachementsAsLinks$AP :					['WebGWDigitManager', 'getDigitAttachementsAsLinks', 'setEmailAttachments'],
	getDigitAttachementsAsLinks$hasAttachment:			['WebGWDigitManager', 'getDigitAttachementsAsLinks', 'messegeHasAttachment'],
	leaveTheService$AP :								['WebGWUserManager', 'leaveService', 'doLeaveTheService'],
    updateDetails$AP :				    				['WebGWUserManager', 'updateDetails', 'doUpdateDetails'],
    resendPrivilegeRequestToSelf$AP :					['WebGWContactManager', 'resendPrivilegeRequestToSelf', 'null'],

	updateCabinetDigitHeaders$doSetMessageReadFlag :	['WebGWDigitManager', 'updateCabinetDigitHeaders', 'null'],

	_empty : []
}

/** general request sender - single exit point */
CM.sendRequest = function() {
	var args = this.toArray(arguments);
	if (args.length == 0){
		throw new Error("Error: missing label for request.");
	}
	var rlabel = args.shift();
	if (typeof gLoader == "object" && gUserState != 'PUBLIC') gLoader.showLoader(rlabel);
	var rlabelArr = this.getLabelArray(rlabel);
	var clss = rlabelArr[0];
	var method = rlabelArr[1];
	if (!this.simulated){
		DWREngine._execute(this.path, clss, method, this.handleResponse, rlabel, args);
	} else {
		 var param = '';
		if (args) param = '["'+args.shift()+'"]';
		var str = clss+"."+method+param;
		this.handleResponse(rlabel, eval(str));
	}
}

/** simulate request - get local data */
CM.simulateRequest = function(){
	this.simulated = true;
	this.sendRequest.apply(this, arguments);
	this.simulated = false;
}

/** general response handler - single entry point */
CM.handleResponse = function(rlabel, reply){
	if (typeof gLoader == "object" && gUserState != 'PUBLIC') gLoader.hideLoader(rlabel);
	var rlabelArr = CM.getLabelArray(rlabel);
	var callback;
	for (var ai=2; ai<rlabelArr.length; ai++){
		try { callback = eval(rlabelArr[ai]); } catch(e){}
		if (callback && callback instanceof Function){
			callback(reply, rlabel);
		}
		if (rlabelArr[ai] == 'gDigitsCacheManager.cacheDigits') return;	// cacheDigits handles calling the rest of the callbacks so don't call them here
	}
	// add history handling here
}

CM.toArray = function (list){
	var arr = [];
	for (var i=0, len=list.length; i<len; i++){
		arr[i] = list[i];
	}
	return arr;
}
CM.getLabelArray = function(rlabel){
	var arr = this.methods[rlabel];
	if (!rlabel || !(arr instanceof Array) || arr.length<3){
		throw new Error("Error: bad label when trying to send request: "+rlabel);
	}
	return arr;
}
CM.handleDwrException = function(message, ex){
	if (typeof gLoader == "object" && gUserState != 'PUBLIC') gLoader.hideLoader('');
	if (ex){
		switch (ex.errorType){
			case "NO_SESSION_FOUND":
				if (typeof beforeLogout != 'undefined') beforeLogout();
//				switchToPublicPage(null, null, false);
				break;
		}
	}
}

DWREngine.setErrorHandler(CM.handleDwrException);
/** menu.js 
copyright 2007 Orr Siloni, Comet Information Systems

API:

// create new menu
myMenu = new Menu("menuId", "menuClass", menuHeaderCunstructor, menuFooterCunstructor);
// menuHeaderCunstructor - optional. Constructor for menu header. should create DOM element and return it.
// menuFooterCunstructor - optional. same as header constructor.
// add items to menu
myMenu.add("text", "action");
myMenu.add("text", "action");

// give previously created item a sub menu
mymenu.startSubMenu("menuClass", menuHeaderCunstructor, menuFooterCunstructor);
	myMenu.add("text", "action");	// added to the sub menu
	myMenu.add("text", "action");	// added to the sub menu
mymenu.endSubMenu();

myMenu.add("text", "action");	// added to the main menu

<a href="javascript:void(0)" onclick="myMenu.show(this);" onmouseout="myMenu.hide(this);">click to open menu</a>
<a href="javascript:void(0)" mouseover="myMenu.show(this);" onmouseout="myMenu.hide(this);">mouse over to open menu</a>

// delete the menu from the DOM
myMenu.remove();

// delete all menus from the DOM
Menu.prototype.removeAll();

*/

var Menu = function(id, clss, header, footer){
	this.subMenus = {};
	this.parentItem = null;
	this.initialize(id, clss, header, footer);
}

Menu.prototype = {
	instances: {},
	
	delimiter: "_",
	
	timeout: 200,
	
	initialize: function(id, clss, header, footer){
		this.createMenu(id, clss, header, footer);
		this.currentOwner = null;	// dom element that triggered showing the menu
		Menu.prototype.instances[this.id] = this;
	},

	createMenu: function(id, clss, header, footer){
		var menuRef = (this.parentItem) ? this.subMenus[this.parentItem.id] : this;
		
		menuRef.id = id;
		menuRef.itemsCount = 0;
		menuRef.timer = null;
		menuRef.menu = document.createElement("div");
		menuRef.menu.id = id;
		menuRef.menu.className = clss;
		menuRef.menu.style.position = "absolute";
		menuRef.menu.style.display = "none";
		
		if (header){
			var menuHeader = header();
			menuRef.menu.appendChild(menuHeader);
		}
		
		menuRef.menuBody = document.createElement("ul");
		menuRef.menu.appendChild(menuRef.menuBody);
		
		if (footer){
			var menuHeader = footer();
			menuRef.menu.appendChild(menuHeader);
		}
		
		if (menuRef.menu.attachEvent){
			if (this.parentItem){
				menuRef.menu.attachEvent("onmouseover", this.overSubMenu);
				menuRef.menu.attachEvent("onmouseout", this.hideSubMenu);
			} else {
				menuRef.menu.attachEvent("onmouseover", this.overMenu);
				menuRef.menu.attachEvent("onmouseout", this.hide);
			}
		} else {
			if (this.parentItem){
				menuRef.menu.addEventListener("mouseover", this.overSubMenu, false);
				menuRef.menu.addEventListener("mouseout", this.hideSubMenu, false);
			} else {
				menuRef.menu.addEventListener("mouseover", this.overMenu, false);
				menuRef.menu.addEventListener("mouseout", this.hide, false);
			}
		}
		
		document.body.appendChild(menuRef.menu);
	},

	startSubMenu: function(clss, header, footer){
		this.parentItem = this.menuBody.lastChild;
		this.parentItem.className = "leftCursor";
		
		if (this.parentItem.attachEvent){
			this.parentItem.attachEvent("onmouseover", this.showSubMenu);
			this.parentItem.attachEvent("onmouseout", this.hideSubMenu);
		} else {
			this.parentItem.addEventListener("mouseover", this.showSubMenu, false);
			this.parentItem.addEventListener("mouseout", this.hideSubMenu, false);
		}
		
		this.subMenus[this.parentItem.id] = {};
		this.createMenu(this.parentItem.id + Menu.prototype.delimiter + "sub", clss, header, footer);
	},

	add: function(text, action, clss, id, tootip){
		var menuRef = (this.parentItem) ? this.subMenus[this.parentItem.id] : this;
		
		var ItemText = document.createTextNode(text); 
		
		var ItemLink;
		if (action){
			ItemLink = document.createElement("a");
			ItemLink.href = "javascript:void(0)";
			if(tootip) ItemLink.title = tootip;
			if (document.all){ // fix for stupid IE
				ItemLink.onclick = function (){ eval(action); }
			} else {
				ItemLink.setAttribute("onclick", action);
			}
			ItemLink.appendChild(ItemText);
		}
		 
		var menuItem = document.createElement("li");
		menuItem.id = menuRef.menu.id + Menu.prototype.delimiter + "i" + (++menuRef.itemsCount);
		if (clss) menuItem.className = clss;
		if (id) menuItem.id = id;
		if (action){ menuItem.appendChild(ItemLink) } else { menuItem.appendChild(ItemText) }
		
		menuRef.menuBody.appendChild(menuItem);
	},

	endSubMenu: function(){
		this.parentItem = null;
	},
	
	show: function(sender, xFF, yFF, xIE, yIE){
		var x=0, y=0;
		if (document.all){
			if (xIE) x=xIE;
			if (yIE) y=yIE;
		} else {
			if (xFF) x=xFF;
			if (yFF) y=yFF;
		}
		var p = Position.cumulativeOffset(sender.parentNode);
//		var p = getElementPosition(sender.parentNode);
		this.currentOwner = sender;
		this.menu.style.left = (p[0] + x - 1) + "px";
		this.menu.style.top = (p[1] + y + sender.parentNode.clientHeight - 10) + "px";
		this.menu.style.display = "block";
	},
	
	overMenu: function(event){
		var o = (event.srcElement) ? event.srcElement : event.target;
		while (o && o.tagName.toLowerCase() != "div"){ o = o.parentNode; }
		
		var menu = Menu.prototype.instances[o.id];
		menu.isOverMenu = true;
		clearTimeout(menu.timer);
	},
	
	hide: function(event){
		var o, menu;
		if (this.menu){
			menu = this;
		} else {	// called by owner
			o = (event.srcElement) ? event.srcElement : event.target; 
			while (o && o.tagName.toLowerCase() != "div"){ o = o.parentNode; }
			menu = Menu.prototype.instances[o.id];
		}
		menu.isOverMenu = false;
		clearTimeout(menu.timer);
		menu.timer = setTimeout("Menu.prototype._hide('"+menu.id+"')", Menu.prototype.timeout);
	},
	_hide: function(id){
		var menu = Menu.prototype.instances[id];
		clearTimeout(menu.timer);
		for (var subMenuId in menu.subMenus){
			Menu.prototype._hideSubMenu(subMenuId);
		}
		menu.menu.style.display = "none";
		if (menu.hideCallBack) menu.hideCallBack();
		menu.currentOwner = null;
	},
	
	showSubMenu: function(event){
		var o = (event.srcElement) ? event.srcElement : event.target; 
		var li = (o.tagName.toLowerCase() == "li")? o : o.parentNode;
		if (!li) return;
		var subMenu = Menu.prototype.getSubMenu(li.id);
		var parentMenu = Menu.prototype.getMenu(li.id);
		clearTimeout(subMenu.timer);
		var p = Position.cumulativeOffset(li);
		subMenu.menu.style.display = "block";
		subMenu.menu.style.left = (p[0] + parentMenu.menu.clientWidth - 10) + "px";
		subMenu.menu.style.top = (p[1] - 10) + "px";
	},
	
	overSubMenu: function(event){
		var o = (event.srcElement) ? event.srcElement : event.target;
		while (o && o.tagName.toLowerCase() != "div"){ o = o.parentNode; }
		
		var id = o.id.substring(0,o.id.indexOf(Menu.prototype.delimiter+"sub"));
		
		var menu = Menu.prototype.getMenu(id);
		menu.isOverSubMenu = true;
		clearTimeout(menu.timer);
		var subMemu = Menu.prototype.getSubMenu(id);
		clearTimeout(subMemu.timer);
	},
	
	hideSubMenu: function(event){
		var o = (event.srcElement) ? event.srcElement : event.target;
		while (o && o.tagName.toLowerCase() != "div" && o.tagName.toLowerCase() != "li"){ o = o.parentNode; }
		
		var subMenu = Menu.prototype.getSubMenu(o.id);
		clearTimeout(subMenu.timer);
		subMenu.timer = setTimeout("Menu.prototype._hideSubMenu('"+o.id+"')", Menu.prototype.timeout);
		
		var menu = Menu.prototype.getMenu(o.id);
		menu.isOverSubMenu = false;
		if (!menu.isOverMenu){
			clearTimeout(menu.timer);
			menu.timer = setTimeout("Menu.prototype._hide('"+menu.id+"')", Menu.prototype.timeout);
		}
	},
	_hideSubMenu: function(id){
		var subMenu = Menu.prototype.getSubMenu(id);
		clearTimeout(subMenu.timer);
		subMenu.menu.style.display = "none";
	},
	
	remove: function(obj){
		if (!obj) obj = this;
		// remove all menu's subs
		for (var sub in obj.subMenus){
			obj.subMenus[sub].menu.parentNode.removeChild(obj.subMenus[sub].menu);
			delete(obj.subMenus[sub]);
		}
		// remove menu
		obj.menu.parentNode.removeChild(obj.menu);
		delete(Menu.prototype.instances[obj.menu.id]);
	},

	removeAll: function(){
		for (var obj in Menu.prototype.instances){
			this.remove(Menu.prototype.instances[obj]);
		}
	},
	
	getMenu: function(id){
		return Menu.prototype.instances[id.substring(0,id.indexOf(Menu.prototype.delimiter))];
	},
	
	getSubMenu: function(id){
		var d = Menu.prototype.delimiter;
		if (id.indexOf(d+"sub") != -1){ id = id.substring(0, id.indexOf(d+"sub")) }
		return Menu.prototype.instances[id.substring(0,id.indexOf(d))].subMenus[id];
	},
	
	setHideCallback: function(callback){
		this.hideCallBack = callback; 
	},
	
	setOwner: function(sender){
		this.currentOwner = sender;
	}
}

/** specific menu headers & footer */

function createImg(clss, src, height, width, alt){
	var el = document.createElement("img");
	el.className = clss;
	el.src = src;
	el.height = height;
	el.width = width;
	el.alt = alt;
	return  el;
}

/* === create menus headers & footers === */
function createDigitMenuHeader(){
	return createImg("displayBlock", gResourcesPath+"images/bg/gallery_DdMenuHeader.gif", "9", "128", "");
}

function createDigitSubMenuHeader(){
	return createImg("displayBlock", gResourcesPath+"images/bg/gallery_DdMenuHComplete.gif", "17", "128", "");
}

function createDigitMenuFooter(){
	return createImg("displayBlock", gResourcesPath+"images/bg/gallery_DdMenuFooter.gif", "17", "128", "");
}

function createSortMenuHeader(){
	return createImg("displayBlock", gResourcesPath+"images/bg/gallery_nDdMenuHeader.gif", "2", "118", "");
}

function createSortMenuFooter(){
	return createImg("displayBlock", gResourcesPath+"images/bg/gallery_nDdMenuFooter.gif", "17", "118", "");
}

function createMoveToFolderMenuHeader(){
	return createImg("displayBlock", gResourcesPath+"images/bg/gallery_mDdMenuHeader.gif", "2", "128", "");
}

function createMoreSingleMediaMenuFooter(){
	return createImg("displayBlock", gResourcesPath+"images/bg/gallery_mDdMenuFooter.gif", "17", "106", "");
}
/*******
 ** Transperant-rounded-cornered box generator
 ** tested on IE6, IE7 and FF 1.5
*******/

/* int class names */
var classBox			= "dialogBox";
var classTop			= "pTop";
var classTopLeft		= "pTopLeft";
var classTopRight		= "pTopRight";

var classLeft			= "pLeft";
var classRight			= "pRight";
var classContent		= "dialogContent";

var classBottom			= "pBottom";
var classBottomLeft		= "pBottomLeft";
var classBottomRight	= "pBottomRight";

/* create the box body */
function makeRoundBox(id) {

	/* create the box block */
	var box = document.createElement('div');
	box.id = id+'Holder';
	box.className = classBox;

	/* create the box top */
	var topBlock = document.createElement("div");
	topBlock.className = classTop;
	var topLeftBlock = document.createElement("div");
	topLeftBlock.className = classTopLeft;
	var topRightBlock = document.createElement("div");
	topRightBlock.className = classTopRight;
	var xButton = document.createElement('div');
	xButton.className = 'pClose';
	xButton.id = id+"Close";
	xButton.onclick = function () { closeDialog(); }
	xButton.onmouseover = function () { changeStyle($(xButton.id),'pClose_on'); }
	xButton.onmousedown = function () { changeStyle($(xButton.id),'pClose_down'); }
	xButton.onmouseout = function () { changeStyle($(xButton.id),'pClose'); }
	xButton.onmouseup = function () { changeStyle($(xButton.id),'pClose_on'); }

	/* add the top block */
	box.appendChild(topBlock);
	topBlock.appendChild(topLeftBlock);
	topBlock.appendChild(topRightBlock);
	topBlock.appendChild(xButton);

	/* create the content box */
	var leftBlock = document.createElement("div");
	leftBlock.className = classLeft;
	var rightBlock = document.createElement("div");
	rightBlock.className = classRight;
	var contentBlock = document.createElement("div");
	contentBlock.className = classContent;
	contentBlock.id = id+'Content';
	/* add the content block */
	box.appendChild(leftBlock);
	leftBlock.appendChild(rightBlock);
	rightBlock.appendChild(contentBlock);

	/* create the box bottom */
	var BottomBlock = document.createElement("div");
	BottomBlock.className = classBottom;
	var BottomLeftBlock = document.createElement("div");
	BottomLeftBlock.className = classBottomLeft;
	var BottomRightBlock = document.createElement("div");
	BottomRightBlock.className = classBottomRight;
	/* add the bottom block */
	box.appendChild(BottomBlock);
	BottomBlock.appendChild(BottomLeftBlock);
	BottomBlock.appendChild(BottomRightBlock);

	/* render the box */
	document.body.appendChild(box);

	return box;
}/*******************************************************************************************
 * Object: Comet Dialog Box
 * Description: Dialog Box Interface
 *******************************************************************************************/

//Static vairables
Dialog.prototype.pageMasker = null;
Dialog.prototype.currentInstance = null;
Dialog.prototype.openedDialogs = new Array();

/*
 * The Dialog object constructor
 * Creates a new Dialog object.
 * boxId: the desired id for the generated dialog box
 */
function Dialog(boxId){
	this.boxId = boxId;
	this.showing = false;
	this.callback = null;
	this.renderBox();
}

Dialog.prototype.setRelativePosition = function(relativeObject, offsetX, offsetY){
	if (relativeObject != null) {
		var p = Position.cumulativeOffset(relativeObject);
		if (offsetX != null) p[0] += offsetX;
		p[1] += offsetY;
		this.relativePosition = p;
		this.relativeObject = relativeObject;
		this.offsetX = offsetX;
		this.offsetY = offsetY;
	} else {
		var p = Position.cumulativeOffset(this.relativeObject);
		if (this.offsetX != null) p[0] += this.offsetX;
		p[1] += this.offsetY;
		this.relativePosition = p;
	}
}

Dialog.prototype.setWidth = function(width) {
	this.width = width;
}

Dialog.prototype.setPageMaskerClass = function(classStr) {
	this.pageMaskerClass = classStr;
}

/* Description: Generating the dialog's interface. */
Dialog.prototype.renderBox = function(){
	//Generating the rounded corners container
	this.container = makeRoundBox(this.boxId);
	this.contentContainer = document.getElementById(this.boxId+'Content');
}

/* Description: Public. Showing the dialog, centering the dialog and applying the page mask */
Dialog.prototype.show = function(){
	var theDialog = this;
	Dialog.prototype.openedDialogs.push(theDialog);
	Dialog.prototype.currentInstance = Dialog.prototype.openedDialogs.length -1; 
	this.showing = true;
	this.container.style.width = (this.width == 'auto') ? this.width : this.width + 'px';
	this.container.style.display = 'block';
	if (document.documentElement.scrollTop && this.relativePosition == null) {
		window.scrollTo(0,0);
	}
	this.centerDialog();
	this.applyPageMask();
	document.onkeydown = function(e){
		theDialog.keyPressed(e);
	}
}

/* Description: Private. Hiding the dialog (used by the close method). */
Dialog.prototype.hide = function(){
	this.container.style.display = 'none';
}

/* Description: Public. Closing the dialog. */
Dialog.prototype.close = function(){
	// carefull that callback doesn't contain a call to close which would lead to an infinite loop.
	if(this.callback) this.callback();
	this.hide();
	this.disablePageMask();
	this.showing = false;
	Dialog.prototype.openedDialogs.pop();
	var len = Dialog.prototype.openedDialogs.length;
	Dialog.prototype.currentInstance = len > 0 ? len-1 : null;
	document.onkeydown = null;
}

/* Description: Creating/enabling the page mask. */
Dialog.prototype.applyPageMask = function(){
	if (this.shouldApplyMask) {
		if (!Dialog.prototype.pageMasker) {
			Dialog.prototype.pageMasker = document.createElement('div');
			document.body.appendChild(Dialog.prototype.pageMasker);
			Dialog.prototype.pageMasker.style.width = getBodyWidth() + 'px';
			Dialog.prototype.pageMasker.style.height = getBodyHeight() + 'px';
		}
		Dialog.prototype.pageMasker.className = this.pageMaskerClass;
		Dialog.prototype.pageMasker.style.display = 'block';
		
		Dialog.prototype.pageMasker.style.zIndex = DialogManager.prototype.baseZindex + Dialog.prototype.openedDialogs.length*10 - 5;
	}
	var currentDialog = Dialog.prototype.openedDialogs[Dialog.prototype.currentInstance];
	currentDialog.container.style.zIndex = parseInt(DialogManager.prototype.baseZindex) + Dialog.prototype.openedDialogs.length*10;
}

/* Description: Disabling the page mask. */
Dialog.prototype.disablePageMask = function(){
	var parentDialog = null;
	if (Dialog.prototype.currentInstance > 0){
		parentDialog = Dialog.prototype.openedDialogs[Dialog.prototype.currentInstance-1];
	}
	if (this.shouldApplyMask && parentDialog && parentDialog.shouldApplyMask){
		Dialog.prototype.pageMasker.style.zIndex = parentDialog.container.style.zIndex -5;
	} else if (Dialog.prototype.pageMasker) {
		Dialog.prototype.pageMasker.style.display = 'none';
	}
}

/*
 * Description: Method for setting the innerHTML of the dialog box.
 * Param html (string): The html to be inserted to the box.
 */
Dialog.prototype.setContent = function(html){
	this.contentContainer.innerHTML = html;
}

/* Description: Handles the key pressing over the dialog. */
Dialog.prototype.keyPressed = function(e){
	var code;
	if (!e) e = window.event;
	switch(e.keyCode){
		case 27: //Esc key
			closeDialog();
			break;
		default:
			break;
	}
}

/* Description: Centers the current dialog */
Dialog.prototype.centerDialog = function(){
	var currentDialog = Dialog.prototype.openedDialogs[Dialog.prototype.currentInstance];
	if (!currentDialog || currentDialog.wasDragged) return;
	var nextTop, nextLeft, windowHeight;
	var windowWidth = document.body.clientWidth;
	if (document.documentElement.scrollTop) {
		windowHeight = document.body.clientHeight - document.documentElement.scrollTop;
	} else {
		windowHeight = document.documentElement.clientHeight;
	}

	if (currentDialog && currentDialog.showing) {
		if (currentDialog.relativePosition != null) {
			currentDialog.setRelativePosition();
			if (currentDialog.offsetX != null){
				currentDialog.container.style.left = currentDialog.relativePosition[0] + "px";
			} else {
				nextLeft = currentDialog.relativePosition[0] + Math.round((currentDialog.relativeObject.clientWidth - currentDialog.container.clientWidth) / 2);
				currentDialog.container.style.left = nextLeft + 'px';
			}
			currentDialog.container.style.top = currentDialog.relativePosition[1] + "px";
		} else {
			nextLeft = Math.round((windowWidth - currentDialog.container.clientWidth) / 2);
			nextTop = Math.round((windowHeight - currentDialog.container.clientHeight) / 2);
			if (nextTop < 0){ nextTop = 0; }
			
			currentDialog.container.style.left = nextLeft + "px";
			currentDialog.container.style.top = nextTop + "px";
		}
	}
	if (Dialog.prototype.pageMasker){
		Dialog.prototype.pageMasker.style.width = getBodyWidth() + 'px';
		Dialog.prototype.pageMasker.style.height = getBodyHeight() + 'px';
	}
	createSlider('messgaeDialog', 'messagesDialogSliderTrack', 'messagesDialogSliderHandle');
}

/* center current dialog */
function centerDialog(){
	Dialog.prototype.openedDialogs[Dialog.prototype.currentInstance].centerDialog();
}

/*
 * Setting the window.resize event for centering the dialog.
 */
function initDialog(){
	if (window.addEventListener){
		window.addEventListener("resize", Dialog.prototype.centerDialog, false);
	} else {
		window.attachEvent("onresize", Dialog.prototype.centerDialog);
	}
}

initDialog();
var DialogManager = function(){}

DialogManager.prototype.getDialogInstance = function(boxId){
	//return new Dialog(boxId, shouldApplyMask);
	return new Dialog(boxId);
}

DialogManager.prototype.dialogObjects = new Array();
DialogManager.prototype.defultWidth = 437;
DialogManager.prototype.baseZindex = 90;

DialogManager.prototype.pageMasks = {
	clear: 'pageMasker',
	screen: 'pageMasker_2'
}

DialogManager.prototype.getPageMaskName = function(clss){
	for (var name in DialogManager.prototype.pageMasks){
		if (clss == DialogManager.prototype.pageMasks[name]) return name;
	}
	return '';
}

DialogManager.prototype.show = function(html, width, mask, callback, hasClose, draggable, relativeContainer, offsetX, offsetY){
	var dialog = null;
	if (DialogManager.prototype.dialogObjects.length <= Dialog.prototype.openedDialogs.length){
		dialog = gDialogManager.getDialogInstance('dialog'+ (DialogManager.prototype.dialogObjects.length+1));
		DialogManager.prototype.dialogObjects.push(dialog);
	} else {
		dialog = DialogManager.prototype.dialogObjects[Dialog.prototype.openedDialogs.length];
	}
	dialog.setContent(html);
	if (relativeContainer != null) {
		dialog.setRelativePosition(relativeContainer, offsetX, offsetY);
	}else{
		dialog.relativePosition = null;
	}
	if (typeof width == "undefined"){
		width = DialogManager.prototype.defultWidth;
	}
	dialog.setWidth(width);
	if (typeof callback == "undefined" || !callback){
		dialog.callback = null;
	} else {
		dialog.callback = callback;
	}
	var xButton = document.getElementById(dialog.boxId+'Close');
	if (!hasClose || !xButton){
		xButton.style.display = 'none';
	}
	if (mask != 'none'){
		dialog.shouldApplyMask = true;
		dialog.setPageMaskerClass(DialogManager.prototype.pageMasks[mask]);
	} else {
		dialog.shouldApplyMask = false;
	}
	dialog.wasDragged = false;
	if (draggable){
		var handle = (draggable === true) ? null : draggable;
		dialog.draggable = new Draggable(dialog.container, {
			handle : handle,
			starteffect:null,
			endeffect:null,
			onStart: function(){
			},
			onEnd: function(draggable, evt){
				dialog.wasDragged = true;
			}
		});
	} else {
		if (dialog.draggable) dialog.draggable.destroy();
	}
	dialog.show();
}
var gToBeUploadedCount = 0;
var gToBeUploadedCountSum = 0; // needed for notifications
var gUploadTransactionsId = new Array(); // needed for notifications

function getFlashUploader(){
	var Flash = null;
	if(document.embeds && document.embeds.length>=1)
		Flash = document.getElementById("EmbedFlashFilesUpload");
	else
		Flash = document.getElementById("FlashFilesUpload");
	return Flash;
}

function submitUploadForm(){
	hideElement('uploadButton');
	$('uploadButtonDisabled').style.display = '';
	var frm = document.getElementById("uploadForm");
	var Flash = getFlashUploader();
	var frmValues = '';
	var uploadId = TransactionId.next();
	gUploadTransactionsId.push(uploadId);
	gToBeUploadedCount = Flash.fileList().length;
	gToBeUploadedCountSum += gToBeUploadedCount;

	frmValues += "albumId=" + frm.albumId.value;
	frmValues += "&sendToPhone=" + (frm.sendToPhoneCheck.checked ? "true" : "false");
	frmValues += "&jsessionid=" + frm.sessionId.value;
//	frmValues += "&digitTempId=" + frm.digitTempId.value;
	frmValues += "&transactionId=" + uploadId;

	if (gToBeUploadedCount == 0){
		var errMsg = TEXT.no_media_was_selected_for_upload;
		$('uploadObjectCont').style.visibility='hidden';
		openDialog('p_error.html', {error:errMsg}, 414, showUploadObject, true, 'screen');
		return false;
	} else {
		gToBeUploadedCount = 0;
	}
	Flash.SetVariable("SubmitFlash", frmValues);
	
	// set upload notification
	hideElement('privilegeNotification');
	var str = TEXT.updating_folder_x_of_y.parse(gUploadedDigitsTotal, gToBeUploadedCountSum);
	if (gOperationFailedSum > 0) str += TEXT.failed_z.parse(gOperationFailedSum);
	if ($('digitUploadText') != null) {
		$('digitUploadText').innerHTML = str;
	}
	displayElement('notificationBox', 'digitUpdate', 'digitUploadLoader');
	gNotificationTimeoutOverride = 5000;
	
	return false;
}

function showUploadObject(){
	makeVisible('uploadObjectCont');
}

function MultiPowUpload_onCompleteAbsolute(type, uploadedBytes){
	closeDialog();
}

function MultiPowUpload_onComplete(type, fileIndex){
}

function MultiPowUpload_onListChange(){
	var tempBeUploadedCount = 0;
	var Flash = getFlashUploader();
	tempBeUploadedCount = Flash.fileList().length;
	if (tempBeUploadedCount > 0){
		hideElement('uploadButtonDisabled');
		$('uploadButton').style.display = '';
	} else {
		hideElement('uploadButton');
		$('uploadButtonDisabled').style.display = '';
	}
}

function cancelUpload(){
	gToBeUploadedCount = 0;
	gToBeUploadedCountSum = 0;
	gUploadedDigitsTotal = 0;
	gOperationFailedSum = 0;
//	hideElement('notificationBox', 'digitUpdate');
	renderMessages();
	closeDialog();
}

function getFileExtension(fileName){
	return (fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase());
}

function submitUploadAvatar(){
	var avatarForm = $("avatarForm");
	var errMsg;
	var fileName = avatarForm.file.value;
	var fileExt = getFileExtension(fileName);
	var gArrImage = new Array("gif","jpg","jpe","jpeg","png","bmp","jpeg");
	var isAllowed = false;
	if (avatarForm.file.value == ''){
		errMsg = TEXT.no_avatar_was_selected;
		openDialog('p_error.html', {error:errMsg}, 414);
		return;
	}
	for (var i=0 ; i < gArrImage.length ; i++) {
    	if (fileExt == gArrImage[i]) {
			isAllowed = true;
			break;
		}
	}
	if (isAllowed){
		avatarForm.submit();
	} else {
		errMsg = TEXT.only_images;
		openDialog('p_error.html', {error:errMsg}, 414);
	}
}

function avatarUploaded(){
	var uploadFrame = $('uploadFrame');
	var doc = uploadFrame.contentWindow || uploadFrame.contentDocument;
	if (doc.document) doc = doc.document;
	if (!doc) return;
	var ref = doc.location.href;
	if (ref == '' || ref == 'about:blank') return;
	
	hideElement("uploadAvatarDialog");
	displayElement("afterUploadAvatarDialog");
	setTimeout(updateAvatar, 1000);
}

function updateAvatar(){
	var avatarSrc = gAlbumspath + "getAvatar?serviceProvider=triplay&lang=" + gLang + "&rnd=" + Math.random();
	var avatarImage = $("avatar_image");
	if (avatarImage) avatarImage.src = avatarSrc;
	var settingsAvatar = $('settingsAvatar');
	if (settingsAvatar) settingsAvatar.src = avatarSrc;
}/** 
 * Copyright (c) 2006, David Spurr (http://www.defusion.org.uk/)
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of the David Spurr nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * http://www.opensource.org/licenses/bsd-license.php
 * 
 * See scriptaculous.js for full scriptaculous licence
 */

var CropDraggable=Class.create();
Object.extend(Object.extend(CropDraggable.prototype,Draggable.prototype),{initialize:function(_1){
this.options=Object.extend({drawMethod:function(){
}},arguments[1]||{});
this.element=$(_1);
this.handle=this.element;
this.delta=this.currentDelta();
this.dragging=false;
this.eventMouseDown=this.initDrag.bindAsEventListener(this);
Event.observe(this.handle,"mousedown",this.eventMouseDown);
Draggables.register(this);
},draw:function(_2){
var _3=Position.cumulativeOffset(this.element);
var d=this.currentDelta();
_3[0]-=d[0];
_3[1]-=d[1];
var p=[0,1].map(function(i){
return (_2[i]-_3[i]-this.offset[i]);
}.bind(this));
this.options.drawMethod(p);
}});
var Cropper={};
Cropper.Img=Class.create();
Cropper.Img.prototype={initialize:function(_7,_8){
this.options=Object.extend({ratioDim:{x:0,y:0},minWidth:0,minHeight:0,displayOnInit:false,onEndCrop:Prototype.emptyFunction,captureKeys:true,onloadCoords:null,maxWidth:0,maxHeight:0},_8||{});
this.img=$(_7);
this.clickCoords={x:0,y:0};
this.dragging=false;
this.resizing=false;
this.isWebKit=/Konqueror|Safari|KHTML/.test(navigator.userAgent);
this.isIE=/MSIE/.test(navigator.userAgent);
this.isOpera8=/Opera\s[1-8]/.test(navigator.userAgent);
this.ratioX=0;
this.ratioY=0;
this.attached=false;
this.fixedWidth=(this.options.maxWidth>0&&(this.options.minWidth>=this.options.maxWidth));
this.fixedHeight=(this.options.maxHeight>0&&(this.options.minHeight>=this.options.maxHeight));
if(typeof this.img=="undefined"){
return;
}
/*$A(document.getElementsByTagName("script")).each(function(s){
if(s.src.match(/cropper\.js/)){
var _a=s.src.replace(/cropper\.js(.*)?/,"");
var _b=document.createElement("link");
_b.rel="stylesheet";
_b.type="text/css";
_b.href=_a+"cropper.css";
_b.media="screen";
document.getElementsByTagName("head")[0].appendChild(_b);
}
});*/
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){
var _c=this.getGCD(this.options.ratioDim.x,this.options.ratioDim.y);
this.ratioX=this.options.ratioDim.x/_c;
this.ratioY=this.options.ratioDim.y/_c;
}
this.subInitialize();
if(this.img.complete||this.isWebKit){
this.onLoad();
}else{
Event.observe(this.img,"load",this.onLoad.bindAsEventListener(this));
}
},getGCD:function(a,b){
if(b==0){
return a;
}
return this.getGCD(b,a%b);
},onLoad:function(){
var _f="imgCrop_";
var _10=this.img.parentNode;
var _11="";
if(this.isOpera8){
_11=" opera8";
}
this.imgWrap=Builder.node("div",{"class":_f+"wrap"+_11});
this.north=Builder.node("div",{"class":_f+"overlay "+_f+"north"},[Builder.node("span")]);
this.east=Builder.node("div",{"class":_f+"overlay "+_f+"east"},[Builder.node("span")]);
this.south=Builder.node("div",{"class":_f+"overlay "+_f+"south"},[Builder.node("span")]);
this.west=Builder.node("div",{"class":_f+"overlay "+_f+"west"},[Builder.node("span")]);
var _12=[this.north,this.east,this.south,this.west];
this.dragArea=Builder.node("div",{"class":_f+"dragArea"},_12);
this.handleN=Builder.node("div",{"class":_f+"handle "+_f+"handleN"});
this.handleNE=Builder.node("div",{"class":_f+"handle "+_f+"handleNE"});
this.handleE=Builder.node("div",{"class":_f+"handle "+_f+"handleE"});
this.handleSE=Builder.node("div",{"class":_f+"handle "+_f+"handleSE"});
this.handleS=Builder.node("div",{"class":_f+"handle "+_f+"handleS"});
this.handleSW=Builder.node("div",{"class":_f+"handle "+_f+"handleSW"});
this.handleW=Builder.node("div",{"class":_f+"handle "+_f+"handleW"});
this.handleNW=Builder.node("div",{"class":_f+"handle "+_f+"handleNW"});
this.selArea=Builder.node("div",{"class":_f+"selArea"},[Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeNorth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeEast"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeSouth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeWest"},[Builder.node("span")]),this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW,Builder.node("div",{"class":_f+"clickArea"})]);
this.imgWrap.appendChild(this.img);
this.imgWrap.appendChild(this.dragArea);
this.dragArea.appendChild(this.selArea);
this.dragArea.appendChild(Builder.node("div",{"class":_f+"clickArea"}));
_10.appendChild(this.imgWrap);
this.startDragBind=this.startDrag.bindAsEventListener(this);
Event.observe(this.dragArea,"mousedown",this.startDragBind);
this.onDragBind=this.onDrag.bindAsEventListener(this);
Event.observe(document,"mousemove",this.onDragBind);
this.endCropBind=this.endCrop.bindAsEventListener(this);
Event.observe(document,"mouseup",this.endCropBind);
this.resizeBind=this.startResize.bindAsEventListener(this);
this.handles=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];
this.registerHandles(true);
if(this.options.captureKeys){
this.keysBind=this.handleKeys.bindAsEventListener(this);
Event.observe(document,"keypress",this.keysBind);
}
new CropDraggable(this.selArea,{drawMethod:this.moveArea.bindAsEventListener(this)});
this.setParams();
},registerHandles:function(_13){
for(var i=0;i<this.handles.length;i++){
var _15=$(this.handles[i]);
if(_13){
var _16=false;
if(this.fixedWidth&&this.fixedHeight){
_16=true;
}else{
if(this.fixedWidth||this.fixedHeight){
var _17=_15.className.match(/([S|N][E|W])$/);
var _18=_15.className.match(/(E|W)$/);
var _19=_15.className.match(/(N|S)$/);
if(_17){
_16=true;
}else{
if(this.fixedWidth&&_18){
_16=true;
}else{
if(this.fixedHeight&&_19){
_16=true;
}
}
}
}
}
if(_16){
_15.hide();
}else{
Event.observe(_15,"mousedown",this.resizeBind);
}
}else{
_15.show();
Event.stopObserving(_15,"mousedown",this.resizeBind);
}
}
},setParams:function(){
this.imgW=this.img.width;
this.imgH=this.img.height;
$(this.north).setStyle({height:0});
$(this.east).setStyle({width:0,height:0});
$(this.south).setStyle({height:0});
$(this.west).setStyle({width:0,height:0});
$(this.imgWrap).setStyle({"width":this.imgW+"px","height":this.imgH+"px"});
$(this.selArea).hide();
var _1a={x1:0,y1:0,x2:0,y2:0};
var _1b=false;
if(this.options.onloadCoords!=null){
_1a=this.cloneCoords(this.options.onloadCoords);
_1b=true;
}else{
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){
_1a.x1=Math.ceil((this.imgW-this.options.ratioDim.x)/2);
_1a.y1=Math.ceil((this.imgH-this.options.ratioDim.y)/2);
_1a.x2=_1a.x1+this.options.ratioDim.x;
_1a.y2=_1a.y1+this.options.ratioDim.y;
_1b=true;
}
}
this.setAreaCoords(_1a,false,false,1);
if(this.options.displayOnInit&&_1b){
this.selArea.show();
this.drawArea();
this.endCrop();
}
this.attached=true;
},remove:function(){
if(this.attached){
this.attached=false;
this.imgWrap.parentNode.insertBefore(this.img,this.imgWrap);
this.imgWrap.parentNode.removeChild(this.imgWrap);
Event.stopObserving(this.dragArea,"mousedown",this.startDragBind);
Event.stopObserving(document,"mousemove",this.onDragBind);
Event.stopObserving(document,"mouseup",this.endCropBind);
this.registerHandles(false);
if(this.options.captureKeys){
Event.stopObserving(document,"keypress",this.keysBind);
}
}
},reset:function(){
if(!this.attached){
this.onLoad();
}else{
this.setParams();
}
this.endCrop();
},handleKeys:function(e){
var dir={x:0,y:0};
if(!this.dragging){
switch(e.keyCode){
case (37):
dir.x=-1;
break;
case (38):
dir.y=-1;
break;
case (39):
dir.x=1;
break;
case (40):
dir.y=1;
break;
}
if(dir.x!=0||dir.y!=0){
if(e.shiftKey){
dir.x*=10;
dir.y*=10;
}
this.moveArea([this.areaCoords.x1+dir.x,this.areaCoords.y1+dir.y]);
Event.stop(e);
}
}
},calcW:function(){
return (this.areaCoords.x2-this.areaCoords.x1);
},calcH:function(){
return (this.areaCoords.y2-this.areaCoords.y1);
},moveArea:function(_1e){
this.setAreaCoords({x1:_1e[0],y1:_1e[1],x2:_1e[0]+this.calcW(),y2:_1e[1]+this.calcH()},true,false);
this.drawArea();
},cloneCoords:function(_1f){
return {x1:_1f.x1,y1:_1f.y1,x2:_1f.x2,y2:_1f.y2};
},setAreaCoords:function(_20,_21,_22,_23,_24){
if(_21){
var _25=_20.x2-_20.x1;
var _26=_20.y2-_20.y1;
if(_20.x1<0){
_20.x1=0;
_20.x2=_25;
}
if(_20.y1<0){
_20.y1=0;
_20.y2=_26;
}
if(_20.x2>this.imgW){
_20.x2=this.imgW;
_20.x1=this.imgW-_25;
}
if(_20.y2>this.imgH){
_20.y2=this.imgH;
_20.y1=this.imgH-_26;
}
}else{
if(_20.x1<0){
_20.x1=0;
}
if(_20.y1<0){
_20.y1=0;
}
if(_20.x2>this.imgW){
_20.x2=this.imgW;
}
if(_20.y2>this.imgH){
_20.y2=this.imgH;
}
if(_23!=null){
if(this.ratioX>0){
this.applyRatio(_20,{x:this.ratioX,y:this.ratioY},_23,_24);
}else{
if(_22){
this.applyRatio(_20,{x:1,y:1},_23,_24);
}
}
var _27=[this.options.minWidth,this.options.minHeight];
var _28=[this.options.maxWidth,this.options.maxHeight];
if(_27[0]>0||_27[1]>0||_28[0]>0||_28[1]>0){
var _29={a1:_20.x1,a2:_20.x2};
var _2a={a1:_20.y1,a2:_20.y2};
var _2b={min:0,max:this.imgW};
var _2c={min:0,max:this.imgH};
if((_27[0]!=0||_27[1]!=0)&&_22){
if(_27[0]>0){
_27[1]=_27[0];
}else{
if(_27[1]>0){
_27[0]=_27[1];
}
}
}
if((_28[0]!=0||_28[0]!=0)&&_22){
if(_28[0]>0&&_28[0]<=_28[1]){
_28[1]=_28[0];
}else{
if(_28[1]>0&&_28[1]<=_28[0]){
_28[0]=_28[1];
}
}
}
if(_27[0]>0){
this.applyDimRestriction(_29,_27[0],_23.x,_2b,"min");
}
if(_27[1]>1){
this.applyDimRestriction(_2a,_27[1],_23.y,_2c,"min");
}
if(_28[0]>0){
this.applyDimRestriction(_29,_28[0],_23.x,_2b,"max");
}
if(_28[1]>1){
this.applyDimRestriction(_2a,_28[1],_23.y,_2c,"max");
}
_20={x1:_29.a1,y1:_2a.a1,x2:_29.a2,y2:_2a.a2};
}
}
}
this.areaCoords=_20;
},applyDimRestriction:function(_2d,val,_2f,_30,_31){
var _32;
if(_31=="min"){
_32=((_2d.a2-_2d.a1)<val);
}else{
_32=((_2d.a2-_2d.a1)>val);
}
if(_32){
if(_2f==1){
_2d.a2=_2d.a1+val;
}else{
_2d.a1=_2d.a2-val;
}
if(_2d.a1<_30.min){
_2d.a1=_30.min;
_2d.a2=val;
}else{
if(_2d.a2>_30.max){
_2d.a1=_30.max-val;
_2d.a2=_30.max;
}
}
}
},applyRatio:function(_33,_34,_35,_36){
var _37;
if(_36=="N"||_36=="S"){
_37=this.applyRatioToAxis({a1:_33.y1,b1:_33.x1,a2:_33.y2,b2:_33.x2},{a:_34.y,b:_34.x},{a:_35.y,b:_35.x},{min:0,max:this.imgW});
_33.x1=_37.b1;
_33.y1=_37.a1;
_33.x2=_37.b2;
_33.y2=_37.a2;
}else{
_37=this.applyRatioToAxis({a1:_33.x1,b1:_33.y1,a2:_33.x2,b2:_33.y2},{a:_34.x,b:_34.y},{a:_35.x,b:_35.y},{min:0,max:this.imgH});
_33.x1=_37.a1;
_33.y1=_37.b1;
_33.x2=_37.a2;
_33.y2=_37.b2;
}
},applyRatioToAxis:function(_38,_39,_3a,_3b){
var _3c=Object.extend(_38,{});
var _3d=_3c.a2-_3c.a1;
var _3e=Math.floor(_3d*_39.b/_39.a);
var _3f;
var _40;
var _41=null;
if(_3a.b==1){
_3f=_3c.b1+_3e;
if(_3f>_3b.max){
_3f=_3b.max;
_41=_3f-_3c.b1;
}
_3c.b2=_3f;
}else{
_3f=_3c.b2-_3e;
if(_3f<_3b.min){
_3f=_3b.min;
_41=_3f+_3c.b2;
}
_3c.b1=_3f;
}
if(_41!=null){
_40=Math.floor(_41*_39.a/_39.b);
if(_3a.a==1){
_3c.a2=_3c.a1+_40;
}else{
_3c.a1=_3c.a1=_3c.a2-_40;
}
}
return _3c;
},drawArea:function(){
var _42=this.calcW();
var _43=this.calcH();
var px="px";
var _45=[this.areaCoords.x1+px,this.areaCoords.y1+px,_42+px,_43+px,this.areaCoords.x2+px,this.areaCoords.y2+px,(this.img.width-this.areaCoords.x2)+px,(this.img.height-this.areaCoords.y2)+px];
var _46=this.selArea.style;
_46.left=_45[0];
_46.top=_45[1];
_46.width=_45[2];
_46.height=_45[3];
var _47=Math.ceil((_42-6)/2)+px;
var _48=Math.ceil((_43-6)/2)+px;
this.handleN.style.left=_47;
this.handleE.style.top=_48;
this.handleS.style.left=_47;
this.handleW.style.top=_48;
this.north.style.height=_45[1];
var _49=this.east.style;
_49.top=_45[1];
_49.height=_45[3];
_49.left=_45[4];
_49.width=_45[6];
var _4a=this.south.style;
_4a.top=_45[5];
_4a.height=_45[7];
var _4b=this.west.style;
_4b.top=_45[1];
_4b.height=_45[3];
_4b.width=_45[0];
this.subDrawArea();
this.forceReRender();
},forceReRender:function(){
if(this.isIE||this.isWebKit){
var n=document.createTextNode(" ");
var d,el,fixEL,i;
if(this.isIE){
fixEl=this.selArea;
}else{
if(this.isWebKit){
fixEl=document.getElementsByClassName("imgCrop_marqueeSouth",this.imgWrap)[0];
d=Builder.node("div","");
d.style.visibility="hidden";
var _4e=["SE","S","SW"];
for(i=0;i<_4e.length;i++){
el=document.getElementsByClassName("imgCrop_handle"+_4e[i],this.selArea)[0];
if(el.childNodes.length){
el.removeChild(el.childNodes[0]);
}
el.appendChild(d);
}
}
}
fixEl.appendChild(n);
fixEl.removeChild(n);
}
},startResize:function(e){
this.startCoords=this.cloneCoords(this.areaCoords);
this.resizing=true;
this.resizeHandle=Event.element(e).classNames().toString().replace(/([^N|NE|E|SE|S|SW|W|NW])+/,"");
Event.stop(e);
},startDrag:function(e){
this.selArea.show();
this.clickCoords=this.getCurPos(e);
this.setAreaCoords({x1:this.clickCoords.x,y1:this.clickCoords.y,x2:this.clickCoords.x,y2:this.clickCoords.y},false,false,null);
this.dragging=true;
this.onDrag(e);
Event.stop(e);
},getCurPos:function(e){
var el=this.imgWrap,wrapOffsets=Position.cumulativeOffset(el);
while(el.nodeName!="BODY"){
wrapOffsets[1]-=el.scrollTop||0;
wrapOffsets[0]-=el.scrollLeft||0;
el=el.parentNode;
}
return curPos={x:Event.pointerX(e)-wrapOffsets[0],y:Event.pointerY(e)-wrapOffsets[1]};
},onDrag:function(e){
if(this.dragging||this.resizing){
var _54=null;
var _55=this.getCurPos(e);
var _56=this.cloneCoords(this.areaCoords);
var _57={x:1,y:1};
if(this.dragging){
if(_55.x<this.clickCoords.x){
_57.x=-1;
}
if(_55.y<this.clickCoords.y){
_57.y=-1;
}
this.transformCoords(_55.x,this.clickCoords.x,_56,"x");
this.transformCoords(_55.y,this.clickCoords.y,_56,"y");
}else{
if(this.resizing){
_54=this.resizeHandle;
if(_54.match(/E/)){
this.transformCoords(_55.x,this.startCoords.x1,_56,"x");
if(_55.x<this.startCoords.x1){
_57.x=-1;
}
}else{
if(_54.match(/W/)){
this.transformCoords(_55.x,this.startCoords.x2,_56,"x");
if(_55.x<this.startCoords.x2){
_57.x=-1;
}
}
}
if(_54.match(/N/)){
this.transformCoords(_55.y,this.startCoords.y2,_56,"y");
if(_55.y<this.startCoords.y2){
_57.y=-1;
}
}else{
if(_54.match(/S/)){
this.transformCoords(_55.y,this.startCoords.y1,_56,"y");
if(_55.y<this.startCoords.y1){
_57.y=-1;
}
}
}
}
}
this.setAreaCoords(_56,false,e.shiftKey,_57,_54);
this.drawArea();
Event.stop(e);
}
},transformCoords:function(_58,_59,_5a,_5b){
var _5c=[_58,_59];
if(_58>_59){
_5c.reverse();
}
_5a[_5b+"1"]=_5c[0];
_5a[_5b+"2"]=_5c[1];
},endCrop:function(){
this.dragging=false;
this.resizing=false;
this.options.onEndCrop(this.areaCoords,{width:this.calcW(),height:this.calcH()});
},subInitialize:function(){
},subDrawArea:function(){
}};
Cropper.ImgWithPreview=Class.create();
Object.extend(Object.extend(Cropper.ImgWithPreview.prototype,Cropper.Img.prototype),{subInitialize:function(){
this.hasPreviewImg=false;
if(typeof (this.options.previewWrap)!="undefined"&&this.options.minWidth>0&&this.options.minHeight>0){
this.previewWrap=$(this.options.previewWrap);
this.previewImg=this.img.cloneNode(false);
this.previewImg.id="imgCrop_"+this.previewImg.id;
this.options.displayOnInit=true;
this.hasPreviewImg=true;
this.previewWrap.addClassName("imgCrop_previewWrap");
this.previewWrap.setStyle({width:this.options.minWidth+"px",height:this.options.minHeight+"px"});
this.previewWrap.appendChild(this.previewImg);
}
},subDrawArea:function(){
if(this.hasPreviewImg){
var _5d=this.calcW();
var _5e=this.calcH();
var _5f={x:this.imgW/_5d,y:this.imgH/_5e};
var _60={x:_5d/this.options.minWidth,y:_5e/this.options.minHeight};
var _61={w:Math.ceil(this.options.minWidth*_5f.x)+"px",h:Math.ceil(this.options.minHeight*_5f.y)+"px",x:"-"+Math.ceil(this.areaCoords.x1/_60.x)+"px",y:"-"+Math.ceil(this.areaCoords.y1/_60.y)+"px"};
var _62=this.previewImg.style;
_62.width=_61.w;
_62.height=_61.h;
_62.left=_61.x;
_62.top=_61.y;
}
}});
JSLogger.prototype.DEBUG = 1;
JSLogger.prototype.INFO = 2;
JSLogger.prototype.ERROR = 3;
JSLogger.prototype.FATAL = 4;

JSLogger.prototype.useStatus = false;
JSLogger.prototype.hideStatusMessage = true;
JSLogger.prototype.statusInterval = 1500;

function JSLogger(level){
	this.level = level;

	if (!JSLogger.prototype.useStatus)
		this.buf = new Array();

	this.setDate = function(buf){
		var d = new Date();
		buf.push(d.getDate());
		buf.push("/");
		buf.push(d.getMonth());
		buf.push("/");
		buf.push(d.getYear());
		buf.push(" ");
		var p = d.getHours();
		if (p < 0)
			buf.push("0");
		buf.push(p);
		buf.push(":");
		p = d.getMinutes();
		if (p < 0)
			buf.push("0");
		buf.push(p);
		buf.push(":");
		p = d.getSeconds();
		if (p < 0)
			buf.push("0");
		buf.push(p);
	}
}

JSLogger.prototype.debug = function(method, message){
	if (this.level == JSLogger.prototype.DEBUG){
		var buf = new Array();
		buf.push("[");
		buf.push(method);
		buf.push("] [DEBUG] [");
		this.setDate(buf);
		buf.push("] [DEBUG] [");
		buf.push(message);
		buf.push("]");

		if (JSLogger.prototype.useStatus)
			window.status = buf.join("");
		else
			this.buf.unshift(buf.join(""));

		if (JSLogger.prototype.hideStatusMessage)
			window.setTimeout("window.status='';", JSLogger.prototype.statusInterval);
	}
}

JSLogger.prototype.info = function(method, message){
	if (this.level <= JSLogger.prototype.INFO){
		var buf = new Array();
		buf.push("[");
		buf.push(method);
		buf.push("] [INFO] [");
		buf.push(message);
		buf.push("]");

		if (JSLogger.prototype.useStatus)
			window.status = buf.join("");

		if (JSLogger.prototype.hideStatusMessage)
			window.setTimeout("window.status='';", JSLogger.prototype.statusInterval);
	}
}

JSLogger.prototype.error = function(method, message, ex){
	if (this.level <= JSLogger.prototype.ERROR){
		var buf = new Array();
		buf.push("[");
		buf.push(method);
		buf.push("] [ERROR] [");
		buf.push(message);
		buf.push("]");

		if (ex != null){
			buf.push(" [");
			buf.push(ex.message);
			buf.push("]");
		}

		if (JSLogger.prototype.useStatus)
			window.status = buf.join("");

		if (JSLogger.prototype.hideStatusMessage)
			window.setTimeout("window.status='';", JSLogger.prototype.statusInterval);
	}
}

JSLogger.prototype.show = function() {
	if (JSLogger.prototype.useStatus) return;

	var div = document.createElement("DIV");
	div.id = "LOGGER_DIV";
	div.style.position = "absolute";
	div.style.top = "0px";
	div.style.left = "0px";
	div.style.backgroundColor = "#666666";
	div.style.color = "#FFFFFF";
	div.style.border = "2px solid #000000";
	div.style.padding = "10px 10px 10px 10px";

	div.innerHTML = "<div align='center'><button onclick='var lgdiv = document.getElementById(\"LOGGER_DIV\");lgdiv.parentNode.removeChild(lgdiv);'>" + TEXT.close + "</button><div align='left'>";

	div.innerHTML += this.buf.join("<br/>");

	div.innerHTML += "</div><br/><div align='center'><button onclick='var lgdiv = document.getElementById(\"LOGGER_DIV\");lgdiv.parentNode.removeChild(lgdiv);'>" + TEXT.close + "</button></div>";

	document.body.appendChild(div);
}

var LOGGER = new JSLogger(JSLogger.prototype.DEBUG);
//Template manager
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
//Ajax management for the template loader
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
tmAjax.prototype.httpRequest = null;
tmAjax.prototype.userAgent = navigator.userAgent.toLowerCase();
tmAjax.prototype.safari = (tmAjax.prototype.userAgent.indexOf('safari') != -1);

tmAjax.prototype.getHttpRequestObject = function() {
	var obj_request = null;
	if (window.XMLHttpRequest) { // if Mozilla, Safari etc
		obj_request = new XMLHttpRequest();
		if (obj_request.overrideMimeType) {
			obj_request.overrideMimeType("text/xml");
		}
	} else if (window.ActiveXObject) { // if IE
		try {
			obj_request = new ActiveXObject("Msxml2.XMLHTTP")
		} catch (e) {
			try {
				obj_request = new ActiveXObject("Microsoft.XMLHTTP")
			} catch (e) {
			}
		}
	}
	return obj_request;
};

tmAjax.prototype.sendRequest = function(url, async, data, callback) {
	try {
		var templatePath = gTemplatesPath;
		var originalURL = url;
		var httpRequest = this.getHttpRequestObject();
		var response = null;

		if (typeof data == "undefined" || data == null) {
			data = "";
			url += "?rnd=" + Math.random()
		} else {
			if (url.indexOf("?") == -1) {
				url += "?";
			}
			url += ("&" + data);
			url += "&rnd=" + Math.random()
		}

		//httpRequest.open("GET", templatePath + url + "&rnd=" + Math.random(), async);
		httpRequest.open("GET", templatePath + url, async);


		if (async == true) {
			httpRequest.onreadystatechange = function() {
				if (httpRequest.readyState == 4) {
					if (tmAjax.prototype.safari || httpRequest.status == 200) {
						//handleResponse(httpRequest.responseXML);
						templateManagerHandleResponse(callback, originalURL, httpRequest.responseText);

					} else {
						LOGGER.error("tmAjax.sendRequest", httpRequest.status + ": There was a problem with the request.");
					}
				}
			};

			httpRequest.send(data);
		} else {
			httpRequest.send(data);
			if (tmAjax.prototype.safari || httpRequest.status == 200)
				return httpRequest.responseText;
			else
				LOGGER.error("tmAjax.sendRequest", httpRequest.status + ": There was a problem with the request.");
		}
	} catch(e) {
		LOGGER.error("tmAjax.sendRequest", httpRequest.status + ": There was a problem with the request.", e);
	}
};

function tmAjax() {
};

//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
//Template Loader
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
//constructor
function TemplateManager(){
	//create the template manager cache object
	this.cache = new Object();
}

/**
 * Load a template synchronous
 */
TemplateManager.prototype.loadSyncd = function(templateName) {
	var data = this.cache[templateName];
	if (data == null){
		LOGGER.debug("loadSyncd", "Template '" + templateName + "' not in cache, loading form server");

		data = tm_ajax.sendRequest(templateName, false, null, null);
		this.cache[templateName] = data;
	}else{
		LOGGER.debug("loadSyncd", "Template '" + templateName + "' found in cache");
	}

	return data;
}

/**
 * Load a template asynchronous
 */
TemplateManager.prototype.load = function(templateName, callback) {
	var data = this.cache[templateName];
	if (data == null){
		LOGGER.debug("load", "Template '" + templateName + "' not in cache, loading form server");
		tm_ajax.sendRequest(templateName, true, null, callback);

	}else{
		LOGGER.debug("load", "Template '" + templateName + "' found in cache");

		callback(templateName, data);
	}
}

TemplateManager.prototype.putInCache = function(templateName, data) {
	this.cache[templateName] = data;
}

/**
 * Parses the template
 * @param value (Optional) The template code
 * @returns The javascript code generated from the parsing
 */
TemplateManager.prototype.parse = function( value ) {
	if ( value == undefined ) {
		value = this.template;
	}
	var out = "";
	var lineNumber = 1;
	try {

		var betweenPerc = false;

		out = "function(context) { \n";

		out += "var __ajp = new TemplateManager();\n";
		out += "var __include;\n";

		out += "try {\n"

		out += "   if ( context == undefined ) { \n";
		out += "	   context = '';\n";
		out += "   }\n";

		out += "var out= unescape('";

		var line = "";

		for (i = 0; i < value.length; i++ )
		{
			var nextTwo = "";
			if ( i <= value.length - 2 ) {
				nextTwo = value.charAt(i) + value.charAt( i + 1 );
			}

			var nextThree = "";
			if ( i <= value.length - 3 ) {
				nextThree = value.charAt(i) + value.charAt( i + 1 ) + value.charAt( i + 2 );
			}

			if ( nextTwo == "<%" && nextThree != "<%=" && nextThree != "<%@") {

				out += "');\n";
				betweenPerc = true;
				i += 1;

			} else if ( nextTwo == "<%" && nextThree == "<%=" && nextThree != "<%@") {

				out += escape(line) + "');\n";
				line = "";
				out += "	out+= ";

				betweenPerc = true;
				i += 2;
			} else if ( nextTwo == "<%" && nextThree != "<%=" && nextThree == "<%@" ) {

				i += 3;
				var directive = "";

				while ( nextTwo != "%>" ) {
					directive += value.charAt(i);
					i++;
						if ( i <= value.length - 2 ) {
							nextTwo = value.charAt(i) + value.charAt( i + 1 );
						}

				}

				out += escape(line) + "');\n";
				line = "";


				out += this._processDirective( directive );
				out += "	out+= unescape('";
				i++;
			} else if ( nextTwo == "%>" ) {
				out += ";\n" + "	out+= unescape('";
				// TODO Throw error if it is off, wrong sintax
				betweenPerc = false;
				i += 1;
			} else if ( value.charAt(i) == String.fromCharCode(10) )  {
				if ( !betweenPerc ) {
					out += escape(line) + "\\n');\n" + "	out+= unescape('";
					line = "";
					lineNumber ++;
				}

			} else if ( value.charAt(i) == String.fromCharCode(13) )  {
			} else {
				if ( betweenPerc ) {
					out += value.charAt(i) ;
				} else {
					line += value.charAt(i);
				}
			}
		}

		out += escape(line) + "');\n";

		out += "} catch (e) {"
		out += "return '"+"An exception occurred while excuting template. Error type: ' + e.name"
			   + "+ '. Error message: ' + e.message;";
		out += "}"
		out += "	return out;\n";
		out += "}\n";
	} catch (e) {

		out = "function(context) { \n";
		out += "return '"+"An exception occurred while parsing on line "+ lineNumber +". Error type: " + e.name
			   + ". Error message: " + e.message+"';";
		out += "}"
	}

	return out;
}

/**
 * Private method. Should not be used externally.
 * @private
 */
TemplateManager.prototype._processDirective = function(directive) {
	var i = 0;

	var tolkenIndex = 0;
	var tolken = new Array();

	//Skip first spaces;
	while ( directive.charAt(i) == ' ' ) {
		i++;
	}

	tolken[tolkenIndex] = "";
	while ( directive.charAt(i) != ' ' && i <= directive.length ) {
		tolken[tolkenIndex] += directive.charAt(i);
		i++;
	}

	tolkenIndex++;

	//Skip first spaces;
	while ( directive.charAt(i) == ' ' ) {
		i++;
	}

	tolken[tolkenIndex] = "";
	while ( directive.charAt(i) != ' ' && directive.charAt(i) != '=' && i <= directive.length ) {
		tolken[tolkenIndex] += directive.charAt(i);
		i++;
	}

	tolkenIndex++;

	//Skip first spaces;
	while ( directive.charAt(i) == ' ' ) {
		i++;
	}

	if( directive.charAt(i) != '=' )
		throw new TemplateManagerException("Sintax error", "Tolken = expected attribute");
	i++

	//Skip first spaces;
	while ( directive.charAt(i) == ' ' ) {
		i++;
	}

	tolken[tolkenIndex] = "";
	while ( directive.charAt(i) != ' ' && i <= directive.length ) {
		tolken[tolkenIndex] += directive.charAt(i);
		i++;
	}
	tolkenIndex++;

	//Skip first spaces;
	while ( directive.charAt(i) == ' ' &&  i <= directive.length ) {
		i++;
	}

	tolken[tolkenIndex] = "";
	while ( directive.charAt(i) != ' ' && directive.charAt(i) != '=' && i <= directive.length && i <= directive.length ) {
		tolken[tolkenIndex] += directive.charAt(i);
		i++;
	}

	tolkenIndex++;

	if( directive.charAt(i) != '='  && i <= directive.length  )
		throw  new TemplateManagerException("Sintax error", "Tolken = expected after attribute" );
	i++

	tolken[tolkenIndex] = "";
	while ( directive.charAt(i) != ' ' && i <= directive.length  && i <= directive.length ) {
		tolken[tolkenIndex] += directive.charAt(i);
		i++;
	}

	var file = "";
	var context = "";

	if ( tolken[0] != "include" )
		throw new TemplateManagerException("Sintax error","Directive " + tolken[0] + " unknown.") ;

	if ( tolken[1] != "file" )
		throw new TemplateManagerException("Sintax error", "Attribute file expected after include." );
	else file = tolken[2];


	if ( tolken[3] != "context" && tolken[3] != "" )
		throw new TemplateManagerException( "Sintax error", "Attribute context expected after file.");
	else if ( tolken[3] == "context" )
		context = tolken[4]
	else
		context = "context";

	var out  = "	__ajp.load("+ file +");\n";
		out += "	__include = __ajp.getProcessor();\n";
		out += "	out+= __include(" + context + ");\n";

	return out;
}

/**
 * Processes the template
 * @param value (Optional) The template code.
 * @returns The output from processing the template
 */
TemplateManager.prototype.process = function( value ) {
	eval ( "var processor =" + this.parse( value ) );
	return processor();
}

/**
 * Get the function that processes the template
 * @param value (Optional) The template code
 * @returns The function that process the template
 */
TemplateManager.prototype.getProcessor = function( value ) {
	eval ( "var processor =" + this.parse( value ) );
	return processor;
}

TemplateManager.prototype.loadAndParse = function(templateName, data, blockId){
	var tmplate = this.loadSyncd(templateName);
	var p = this.getProcessor(tmplate);

	if (blockId) {
		document.getElementById(blockId).innerHTML = p({DATA:data});
		return templateName;
	} else {
		return  p({DATA:data});
	}
}

/**
 * Exception throwed by TemplateManager
 */
TemplateManagerException = function( name, message ) {
	this.name = name;
	this.message = message;
}

function templateManagerHandleResponse(callback, templateName, data){
	TM.putInCache(templateName, data);
	callback(templateName, data);
}

var TM = new TemplateManager();
var tm_ajax = new tmAjax();
/** service.js 
 includes service and convinience functions
 or functions that are used to connect between 
 generic libraries and application implementation
*/

var gUrlPartsCountAlbums = 4;
var gUrlPartsCountAlbum = 5;
var gUrlPartsUsernameIndex = 3;
var gUrlPartsLabelIndex = 4

/* Get URL Parameters Using Javascript
An easy way to parse the query string in your URL to grab certain values.

obtained from: http://www.netlobo.com/url_query_string_javascript.html
*/
function getQueryStringParams(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

/* complementray to dhtml_history.js - breaks the history to context & params */
function getHistoryData(newLocation){
	var context = newLocation.substring(0,newLocation.indexOf(";"));
	var arr = newLocation.substring(newLocation.indexOf(";") + 1).split("&");
	var tmp = null;
	var params = [];
	for (var i=0; i<arr.length; i++){
		try {
			tmp = arr[i].split("=");
			params[tmp[0]] = tmp[1];
		} catch(e){}
	}
	return {context:context, params:params};
}

/* change className of obj to clss */
function changeStyle(obj,clss){
	obj.className = clss;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function displayElement(){
	$A(arguments).flatten().each(function(el){
		el = $(el);
		if (el) el.style.display = 'block';
	});
}
function hideElement(){
	$A(arguments).flatten().each(function(el){
		el = $(el);
		if (el) el.style.display = 'none';
	});
}

function toggleElement(){
	$A(arguments).flatten().each(function(el){
		el = $(el).style;
		if (el){
			if (el.display == 'block'){
				el.display = 'none';
			} else {
				el.display = 'block';
			}
		}
	});
}

/* make visible */
function makeVisible(id){
	var el = $(id);
	if (!el) return;
	el.style.visibility = 'visible';
}
/* make hidden */
function makeHidden(id){
	var el = $(id);
	if (!el) return;
	el.style.visibility = 'hidden';
}

function openMenu(menuToClose, menuToOpen) {
	hideElement(menuToClose);
	displayElement(menuToOpen);
}

function imageSource(src,width,height,alt){
	document.write('<img src="'+ src +'" width="'+ width +'" height="'+ height +'" alt="'+ alt +'" />')
}

/* get base url */
function getBaseUrl(){
	return "http://" + gAPP + gBasepath.replace(/\/$/, '');
}
/* get triplay home url */
function getHomeUrl(){
	return "http://" + gWWW;
}

/* create albums query */
function createAlbumsQuery(){
	var obj = new Object();
	obj.albumsSortBy = gAlbumsSortBy;
	obj.sortDirection = gAlbumSortDir;
	obj.from = 1;
	obj.numEntities = 96;
	obj.calculateTotalFlag = true;
	return obj;
}
/* create public albums query */
function createPublicAlbumsQuery(){
	var obj = new Object();
	obj.albumsSortBy = "CREATION_TIME";
	obj.sortDirection = "DESC";
	obj.from = 1;
	obj.numEntities = 96;
	obj.calculateTotalFlag = true;
	return obj;
}
/* create public album URL info */
function createPublicAlbumsUrlInfo() {
	var obj = new Object();
	obj.albumUrlType = '';
	obj.digitId = '';
	obj.labelId = '';
	obj.username = '';
	return obj;
}

/* create digits operation query */
function createDigitsOperationQuery(digitList, operType, moveTo){
	var arr = [], labelIds;
	/* Bug 3596 fix, ensure that original operation type is preserved so the DELETE_OBJECT condition is hit on every cycle and */
	/* no only on the first cycle */
	var originalOperType = operType; /* Preserve original operation */
	for (var i = 0; i < digitList.length ; i++){
		if (moveTo){
			labelIds = [moveTo];
			if (moveTo != gSystemLabels.TRASH && (digitList[i].labelIds && digitList[i].labelIds.include(gSystemLabels.RECENTLY_RECEIVED) || gAlbumId == gSystemLabels.RECENTLY_RECEIVED)){
				labelIds.push(gSystemLabels.INBOX);
			}
		} else {
			labelIds = digitList[i].labelIds;
		}
		if (!labelIds && gAlbumId) {
            labelIds = [gAlbumId];
        } else if (originalOperType == "DELETE_OBJECT") {
        	if (gAlbumId == gSystemLabels.RECENTLY_RECEIVED) {
	            //Added by Rami Gabai to resolve bug #3376
	            operType = "UPDATE_OBJECT";
       	}
            var tmpArr = new Array();
            for (var k = 0; k < labelIds.length; k++){
                if (labelIds[k] != gAlbumId){
                    tmpArr.push(labelIds[k]);
                }
            }
            labelIds = tmpArr;
        }

        arr.push( {
			operationType : operType,
			cabinetDigitHeader : new CabinetDigitHeader(digitList[i], gUser.userId, labelIds)
		} );
	}
	return arr;
}

/* create cabinet digit header */
function CabinetDigitHeader(digit, userId, labelIds){
	this.digitId = digit.digitId || null;
	this.userId = userId || null;
	this.readFlag = !!digit.readFlag;
	this.caption = digit.digitCaption || '';
	this.rotationDegrees = digit.rotationDegrees || 0;
	this.labelIds = labelIds || [];
}

/* set digits sort */
function setDigitsSortBy(sortBy){
	gDigitsCacheManager.setSort(sortBy);
	gDigitsSortBy = gDigitsCacheManager.sortBy;
	gDigitSortDir = gDigitsCacheManager.sortDir;
	
	gDigitsCacheManager.getDigits(gAlbumId, 1, gDigitsCache[gAlbumId].album.numMedia, 'cacheDigits$renderAlbumPage');
}

/* === STRING EXTENTIONS === */
/* get short string */
String.prototype.shorten = function(len, more){
	return (this.length > len) ? this.substring(0,len) + $N(more, '') : this;
}

String.prototype.trim = function(){
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function(){
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function(){
	return this.replace(/\s+$/,"");
}
String.prototype.pad = function(length, fill, dir){
	if (this.length >= length || !fill) return this;
	var padding = '';
	while (padding.length + this.length < length) padding += fill;
	padding = padding.shorten(length - this.length);
	return (dir == 'right') ? this+padding : padding+this;
}
String.prototype.lpad = function(length, fill){
	return this.pad(length, fill, 'left');
}
String.prototype.rpad = function(length, fill){
	return this.pad(length, fill, 'right');
}
String.prototype.parse = function(){
	if (this.indexOf('$#') == -1) return this;
	var arr = $A(arguments), str = this;
	while (str.indexOf('$#') != -1 && arr.length > 0){ str = str.replace('$#', arr.shift()); }
	return str;
}
Number.prototype.toCommaSeparated = function(){
	return this.toString().split('').reverse().join('').replace(/(\d{3})(?=\d)/g,'$1,').split('').reverse().join('');
}

/* get document body height */
function getBodyHeight(){
	if (document.documentElement){
		return document.documentElement.scrollHeight;
	} else if (document.body && typeof document.body.scrollHeight != 'undefined'){
		return document.body.scrollHeight;
	}
	return 0;
}
/* get document body width */
function getBodyWidth(){
	if (document.documentElement){
		return document.documentElement.scrollWidth;
	} else if (document.body && typeof document.body.scrollWidth != 'undefined'){
		return document.body.scrollWidth;
	}
	return 0;
}

/* show tool tip */
function showTooltip(tId){
	openDialog('p_inappropriateMedia.html',null , 414);
}

/* get digit id from obj id */
function getDigitIdFromObjId(id){
	return id.substring(id.indexOf('digit_')+6);
}

/* set out of digit class name (normal or multiple selected) */
function setDigitOutStyle(obj){
	var digitId = getDigitIdFromObjId(obj.id);
	if (gArrSelectedDigits.include(digitId)){
		changeStyle(obj, 'multiple_collection');
	} else {
		changeStyle(obj, 'single_picture');
	}
}

/* count and set number of chars in element */
function setCharsCount(elem, limit, printed, dir){
	if (!limit) return;
	var str = elem.value;
	var strlen = str.length;
	if (printed) printed = $(printed);

    if (dir > 0) {
        if (strlen > limit) {
            printed.style.display = "none"; // hide counter if the count is zero
        } else {
            printed.style.display = "block"; // hide counter if the count is zero
        }
    }
    if (strlen <= limit){
		if (printed){
			if (dir > 0){
				printed.innerHTML = strlen;
			} else {
				printed.innerHTML = (limit - strlen);
			}
		}
		return true;
	} else {
        if (dir < 0) {
            elem.value = str.substr(0, limit);
        }
        return false;
	}
}

/* sets default text in a textarea */
function setDeafultMessage(elem, isFocus, message, defClss, clss){
	var str = elem.value;
	if (isFocus){
		if (str == message){
			elem.value = '';
			if (clss) elem.className = clss;
		}
	} else {
		if (str == ''){
			if (defClss) elem.className = defClss;
			elem.value = message;
			$I('quick_message_chars', '');
		}
	}
}

function setTextAlign(el, defValue){
	el = $(el);
	$(el).style.textAlign =  (el.value == defValue) ? 'center' : 'left';
}

/* normalize value */
function $N(v, def){
	if (!$is(def)) def = null;
	return (!$is(v) || v == null || v == '') ? def : v;
}

/* check if param is defined */
function $is(v){ return typeof v != 'undefined'; }

/* safer document.getElementById(id),innerHTML=html */
function $I(el, content, append){
	el = $(el);
	if (!el) return null;
	var prop = (el.tagName.toLowerCase() == 'input') ? 'value' : 'innerHTML';
	return $is(content) ? (append) ? el[prop] += content : el[prop] = content : el[prop];
}



/* create recipients from query */
function createRecipientsFromQuery(fAddress){
	var arr = $(fAddress).value.split(/\s*,\s*/);
	var result = [];
	var address, recipientType, mobile, recipientId;
	var errorsFound = false;
	for (var i=0; i<arr.length; i++){
		/* Bug fix, ensure that case sensitivity won't harm the identification of 'Me' */
		if (arr[i].toLowerCase() == TEXT.me.toLowerCase()) {
			arr[i] = gUser.username;
		}
		address = arr[i];
		if (!address){ continue; }
		if (isEmail(address)){
			recipientType = "EMAIL";
		} else {

            mobile = validateNumber(address);
			if (mobile){
				address = mobile;
				recipientType = "MSISDN";
			} else {
				recipientType = "RECIPIENT_USER";
			}
		}
		if (arr[i] == gUser.username) {
			recipientId = gUser.userId;	
		} else {
			recipientId = getRecipientId(address);
		}
		if (recipientType == "RECIPIENT_USER") { // Only test validity if type is recipient user
			if (recipientId == null) {
				errorsFound = true;
			}
		}
		result.push(new RecipientTO(recipientId, address, recipientType));
	}
	
	if (errorsFound) {
		var quick_searchFriendsCont = $("quick_searchFriendsCont");
		if (!quick_searchFriendsCont) {
			showErrors(result);
			return (null);
		}		
	}
	return result;
}

function showErrors(recipients) {
	errMsg = TEXT.delivery_status_message + '<br/>';
	for (var i = 0; i < recipients.length; i++) {
		if (recipients[i].recipientId == null) { // Check only defective recipients
			errMsg += '<br/>' + anaylzeError(recipients[i].requestedAddress) + '<br/>';
		}
	}
	
	errMsg += '<br/>'
	openDialog('p_error.html',{error:errMsg, showButton:true, buttonText:TEXT.ok, title:TEXT.delivery_status_notification, style:true, focusAt:'quick_message_to'}, 300, null, null, null, null, null, $('messageComposer'), 20, 0);	
}

/* get recipient id by address or username */
function getRecipientId(address){
	if (!gUserContactsList) return null;
	// look for the id in contacts
	for (var i=0; i<gUserContactsList.length; i++){
		if (address == gUserContactsList[i].username ||
			address == gUserContactsList[i].addresses.mobile || 
			address == gUserContactsList[i].addresses.email){
			return gUserContactsList[i].contactUserId;
		}
	}
	// look for the id in inbox digit cache
	if (gDigitsCache[gSystemLabels.INBOX]){
		var digit;
		for (var digitId in gDigitsCache[gSystemLabels.INBOX].digits){
			digit = gDigitsCache[gSystemLabels.INBOX].digits[digitId];
			if (address == digit.senderNickname) return digit.senderId;
			for (var i=0; i < digit.recipients.length; i++){
				if (address == digit.recipients[i].requestedAddress) return digit.recipients[i].recipientId;
			}
		}
	}
	return null;
}

/* is email */
function isEmail(emailStr){
	/* set email string to lower case */
	emailStr = emailStr.toLowerCase();
	
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	
	if (emailStr.indexOf("%") >= 0)
		return false;

	if (matchArray==null){
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];

	for (i=0; i<user.length; i++){
		if (user.charCodeAt(i)>127){
			return false;
		}
	}
	for (i=0; i<domain.length; i++){
		if (domain.charCodeAt(i)>127){
			return false;
		}
	}
	if (user.match(userPat)==null){
		return false;
	}

	var IPArray=domain.match(ipDomainPat);
		if (IPArray!=null){
			for (var i=1;i<=4;i++){
				if (IPArray[i]>255){
				return false;
			}
		}
		return true;
	}

	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++){
		if (domArr[i].search(atomPat)==-1){
			return false;
		}
	}

	if (checkTLD && domArr[domArr.length-1].length!=2 &&
		domArr[domArr.length-1].search(knownDomsPat)==-1){
		return false;
	}

	return (len>=2); 
	//return (true); /* As long as the format is correct ignore the number of dots */
}

function cleanNumber(phone) {
    return phone.replace(/[()+\- ]/g, '');
}

/* validate number */
function validateNumber(INNUM){
	INNUM = INNUM + "";
	INNUM = cleanNumber(INNUM);
	var OUTNUM = "";
	var errCode = 0;
	
	if (INNUM.length >= 8 && INNUM.length <= 14 && /^\+?\d+$/.test(INNUM)){
		if (INNUM.indexOf("+") == 0) {
			OUTNUM = INNUM.substring(1);
		} else if (INNUM.indexOf("00") == 0) {
			OUTNUM = INNUM.substring(2);
		} else if (INNUM.indexOf("0") == 0 && INNUM.length <= 12){
			if (gCountryCode == null || gCountryCode == 1)
				OUTNUM = null;
			else
				OUTNUM = gCountryCode + INNUM.substring(1);
		} else if(INNUM.indexOf("0") != 0 && INNUM.length == 10 && gCountryCode == 1) {
			OUTNUM = gCountryCode + INNUM;
		} else if (INNUM.indexOf("0") != 0 && INNUM.length >= 9) {
			OUTNUM = INNUM;
		} else
			OUTNUM = null;
	}else{
		OUTNUM = null;
	}
	return OUTNUM;
}

/* remove country code from the mobile number and add a leading zero */
function mobileToLocal(mobile){
	if (!mobile) return false;
    // Fixed mobileToLocal condition to match longer numbers
    if (mobile.indexOf(gCountryCode) == 0 && (gCountryCode != 1 || (gCountryCode == 1 &&  mobile.length > 12))){
		var regEx = eval('/^'+gCountryCode+'/');
		mobile = mobile.replace(regEx, 0);
	}
	return mobile;
}

function copyPropertyFromChildElements(origin, target, tag, itemNum, prop){
	if (prop == 'innerHTML'){
		target.getElementsByTagName(tag)[itemNum].innerHTML = origin.getElementsByTagName(tag)[itemNum].innerHTML;
	} else {
		target.getElementsByTagName(tag)[itemNum].setAttribute(prop, origin.getElementsByTagName(tag)[itemNum].getAttribute(prop));
	}
}

/* insert node into DOM after refnode */
function insertAfter(node, refnode){
	return refnode.parentNode.insertBefore(node, refnode.nextSibling);
}

/* added functionality for Script.aculo.us Slider */
if (!Control) var Control = { Slider: function(){} }
Control.Slider.prototype.calcLengths = function(){
	this.trackLength = this.maximumOffset() - this.minimumOffset();
	
	this.handleLength = this.isVertical() ? 
      (this.handles[0].offsetHeight != 0 ? 
        this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) : 
      (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth : 
        this.handles[0].style.width.replace(/px$/,""));
}

/* return date for midnight today */
function Today(){
	var today = new Date();
	today.setHours(0);
	today.setMinutes(0);
	today.setSeconds(0);
	today.setMilliseconds(0);
	return today;
}

/* transaction Id creator */
var TransactionId = {
	//value : parseInt(Math.random().toString().substring(2)),
	// generate 6 digit number between 100,000 - 900,000
	value : Math.floor(Math.random()*800000)+100000,
	next : function (){
		return ++this.value;
	}
}

/* open contact public page */
function openContactPublicPage(userId, albumId) {
	if (!albumId) albumId = '';
	window.location.href = gBasepath + userId + "/" + albumId;
}

function openWindow(url) {
	window.open(url,'TPgeneral','width=900,height=720,top=0,left=0,scrollbars=1,resizable=1,location=1,toolbar=1,status=1,menubar=1');
}
function openTerms(){openWindow(URLs.terms);}
function openPrivacy(){openWindow(URLs.privacy);}
function openContact(){openWindow(URLs.contact);}
function openFeedback(){openWindow(URLs.feedback);}
function openHelp(){openWindow(URLs.help);}


/* start functions used to set skin/language */
function loadScript(url) {
	var html_doc = document.getElementsByTagName('head')[0];
	var js = document.createElement('script');
	js.setAttribute('type', 'text/javascript');
	js.setAttribute('src', url);
	html_doc.appendChild(js);

	return false;
}

function loadCSS(url) {
	var html_doc = document.getElementsByTagName('head')[0];
	var css = document.createElement('link');
	css.setAttribute('rel', 'stylesheet');
	css.setAttribute('type', 'text/css');
	css.setAttribute('href', url);
	html_doc.appendChild(css);

	// alert state change
	css.onreadystatechange = function() {
		if (css.readyState == 'complete') {}
	}
	css.onload = function() {}
	return false;
}

function setLang() {
	var lang = getQueryStringParams('lang');
	if (lang){
		gLang = lang;
		if (typeof getL18NModeFromCookie != 'undefined'){
			getL18NModeFromCookie();
			gDataCookieWithCountry.lang = lang;
			writeL18NModeToCookie();
		}
	} else if (typeof getL18NModeFromCookie != 'undefined'){
		lang = getL18NModeFromCookie('lang');
		if (lang) gLang = lang;
	} else if(unescape(document.cookie).indexOf('"lang": "de"')>-1){
		gLang = 'de';
	}
	loadScript(gResourcesPath + "js/" + gLang + ".js?version=1.57.4.13758");
	loadCSS(gResourcesPath + "css/" + gLang + ".css?version=1.57.4.13758");
}
function insertText() {
	var textColl = document.getElementsByClassName('txt');
	for (var i=0, j=textColl.length; i < j; i++) {
		if (textColl[i].tagName.toLowerCase() != "input") {
			if (TEXT[textColl[i].id]) textColl[i].innerHTML = TEXT[textColl[i].id];
		} else {
			if (TEXT[textColl[i].id]) textColl[i].value = TEXT[textColl[i].id];
		}
	}
	var imgColl = document.getElementsByClassName('img');
	for (var i=0, j=imgColl.length; i < j; i++) {
		if (IMG[imgColl[i].id]) imgColl[i].src = IMG[imgColl[i].id];
	}
}

/* get formatted date */
function getFormattedDate(date, format){
	/* yyyy - full year; yy - 2 digit year; MM - month; dd - day;
	   hh - hour; mm - minute; ss - seconds;
	   wk - abbreviated weekday; WK - weekday; */
	function padZero(value) {
		return value.toString().lpad(2,'0');
	}

	if (!date) date = new Date();
	if (!format) format = 'dd/MM/yyyy';	// default format
	var day = padZero(date.getDate());
	var month = padZero(date.getMonth()+1);
	var yearLong = date.getFullYear();
	var yearShort = date.getFullYear().toString().substring(2,4);
	var year = (format.indexOf("yyyy") > -1) ? yearLong : yearShort;
	var hour = padZero(date.getHours());
	var minute = padZero(date.getMinutes());
	var second = padZero(date.getSeconds());
	var weekday = TEXT.weekdays[date.getDay()];
	return format.replace('dd', day).replace('MM', month).replace(/y{1,4}/, year).replace('hh', hour).replace('mm', minute).replace('ss', second).replace('WK', weekday).replace('wk', weekday.substring(0,3));
}

function changeLang(lang){
	if (lang == gLang) return;
	var params = getSetParam('set', 'lang', lang);
	var url;
	if (params){
		url = location.pathname + params + location.hash;
	} else {
		var con = (location.search) ? '&' : '?';
		url = location.pathname + location.search + con + 'lang=' + lang + location.hash;
	}
	if (gDataCookie){
		gDataCookieWithCountry.lang = lang;
		writeL18NModeToCookie();
	}
	location.href = url;
}

function getSetParam(type, param, value){
	var params = location.search.toString();
	if (!params) return null;
	params = params.substring(1).split('&');
	var arr, found = false;
	for (var i=0; i < params.length; i++){
		arr = params[i].split('=');
		if (arr[0] == param){
			if (type == 'get') return arr[1];
			params[i] = param+'='+value;	// if type == 'set'
			found = true;
			break;
		}
	}
	if (!found) params.push(param+'='+value);
	params = '?' + params.join('&');
	return (type == 'set') ? params : null;
}
/* end functions used to set skin/language */

/* script.aculo.us Autocompleter.Base extension to support 2 array: one for update & one for display */
Autocompleter.Base.prototype.updateElement = function(selectedElement){
	if (this.options.updateElement) {
		this.options.updateElement(selectedElement);
		return;
	}
	var value = '';
	if (this.options.select) {
		var nodes = document.getElementsByClassName(this.options.select, selectedElement) || [];
		if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
	} else {
		if (this.options.displayArray){	// condition added by Orr Siloni
			value = this.options.array[parseInt(selectedElement.id.substring(selectedElement.id.lastIndexOf('_')+1))];
		} else {
			value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
		}
	}

	var lastTokenPos = this.findLastToken();
	if (lastTokenPos != -1) {
		var newValue = this.element.value.substr(0, lastTokenPos + 1);
		var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/);
		if (whitespace) newValue += whitespace[0];
		this.element.value = newValue + value;
	} else {
		this.element.value = value;
	}
	this.element.focus();

	if (this.options.afterUpdateElement)
		this.options.afterUpdateElement(this.element, selectedElement);
}
/* script.aculo.us Autocompleter.Local extension to support 2 array: one for update & one for display */
Autocompleter.Local.prototype.initialize = function(element, update, array, options) {
	this.baseInitialize(element, update, options);
	this.options.array = array;
	this.options.displayArray = options.displayArray || false;	// line added by Orr Siloni
}
Autocompleter.Local.prototype.setOptions = function(options){
	this.options = Object.extend({
		choices: 10,
		partialSearch: false,
		partialChars: 2,
		ignoreCase: true,
		fullSearch: options.fullSearch || false,
		maxHeight : '12em',
		selector: function(instance){
			var ret       = []; // Beginning matches
			var partial   = []; // Inside matches
			var entry     = instance.getToken();
			var count     = 0;
			var entryId   = '';
			var elem;

			for (var i = 0; i < instance.options.array.length &&  ret.length < instance.options.choices ; i++){
				if (instance.options.displayArray){	// condition added by Orr Siloni
					elem = instance.options.displayArray[i];
					entryId = ' id="' + instance.update.id + '_li_' + i + '"';
				} else {
					elem = instance.options.array[i];
				}
				var foundPos = instance.options.ignoreCase ? elem.toLowerCase().indexOf(entry.toLowerCase()) : elem.indexOf(entry);
				while (foundPos != -1) {
					if (foundPos == 0 && elem.length != entry.length) {
						ret.push("<li"+entryId+"><strong>" + elem.substr(0, entry.length) + "</strong>" + elem.substr(entry.length) + "</li>"); 	// 'entryId' added by Orr Siloni
						break;
					} else if (entry.length >= instance.options.partialChars && instance.options.partialSearch && foundPos != -1) {
						if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
							partial.push("<li"+entryId+">" + elem.substr(0, foundPos) + "<strong>" + elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(foundPos + entry.length) + "</li>");
							break;
						}
					}
					foundPos = instance.options.ignoreCase ? elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : elem.indexOf(entry, foundPos + 1);
				}
			}
			if (partial.length)
				ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
			var style = (ret.length > 10) ? 'height:' + instance.options.maxHeight + ';overflow:hidden;' : '';
			return '<ul id="' + instance.element.id + '_ul" style="float:left;' + style + '">' + ret.join('') + '</ul>';
		}
	}, options || {});
}
Autocompleter.Local.prototype.updateChoices = function(choices) {
	function slider(id, maxHeight){
		return '<div id="' + id + 'SliderTrack" class="acSliderTrack" style="display:none;height:' + maxHeight + ';top:-' + maxHeight + ';">' +
			'<div id="' + id + 'SliderHandle" class="sliderHandle"><img src="' + gResourcesPath + 'images/bg/sliderTrack.jpg" width="8" height="100%" alt="" /></div>' +
		'</div>';
	}
	if(!this.changed && this.hasFocus) {
		var matches = choices.match(/<li/g);
		if (matches && matches.length > 10){
			this.update.innerHTML = choices + slider(this.element.id, this.options.maxHeight);
			this.update.style.height = this.options.maxHeight;
		} else {
			this.update.innerHTML = choices;
			this.update.style.height = 'auto';

		}
		Element.cleanWhitespace(this.update);
		Element.cleanWhitespace(this.update.down());

		if(this.update.firstChild && this.update.down().childNodes) {
			this.entryCount = this.update.down().childNodes.length;
			for (var i = 0; i < this.entryCount; i++) {
				var entry = this.getEntry(i);
				entry.autocompleteIndex = i;
				this.addObservers(entry);
			}
		} else {
			this.entryCount = 0;
		}

		this.stopIndicator();
		this.index = 0;

		if(this.entryCount==1 && this.options.autoSelect) {
			this.selectEntry();
			this.hide();
		} else {
			this.render();
		}
		var id = this.element.id;
        if (id != 'quick_message_to_connect') {
            if (matches && matches.length > 10) setTimeout("createSlider('" + id + "_ul', '" + id + "SliderTrack', '" + id + "SliderHandle');", 100);
        }
//		createSlider(id + '_ul', id + 'SliderTrack', id + 'SliderHandle');
	}
}
function autoCompleterOnShow(element, update){
	if(!update.style.position || update.style.position=='absolute'){
		update.style.position = 'absolute';
		Position.clone(element, update, {
			setHeight: false,
			offsetTop: element.offsetHeight
		});
	}
	Effect.Appear(update,{duration:0.15});
	createSlider('autoCompleteCont', 'autoCompleteSliderTrack', 'autoCompleteSliderHandle');
};

var gWhatsThisShowing = false;

function getElementLeftPosition(e) {
	var x = 0;
	while (e) {
		x += e.offsetLeft;
		e = e.offsetParent;
	}
	return x;
}

function getElementTopPosition(e) {
	var y = 0;
	while (e) {
		y += e.offsetTop;
		e = e.offsetParent;
	}
	return y;
}

function closeWhatsThisPopup(){
	Effect.Fade('whatsThisPopup',{duration: .25});
	gWhatsThisShowing = false;
}

/* Whats This Baloon */
function whatsThis(e,textToDisplay){
    var whatsThisElement = $('whatsThisPopup');
    if(textToDisplay=='the_items_you_put'){
		textToDisplay = TEXT.the_items_you_put
	}else if(textToDisplay=='deWhatDoYouNeed'){
		textToDisplay = TEXT.to_insure_your_privacy
	}else if(textToDisplay=='edit_a_member'){
		textToDisplay = TEXT.changes_2Member_can_only_e_made
	}else if(textToDisplay=='edit_a_friend'){
		textToDisplay = TEXT.changes_2Friend_can_only_e_made
	}
	if (!whatsThisElement){
		whatsThisElement = document.createElement("div");
		whatsThisElement.id = 'whatsThisPopup';
		whatsThisElement.className = 'whatsThisComponent';
		whatsThisElement.style.display = 'none';
		document.body.appendChild(whatsThisElement);
	}
    whatsThisElement.innerHTML = [
	'<img src="/WebGW/pages/triplay/images/bg/whats_thisTop.gif" class="displayNone" alt="" />',
	'<img src="/WebGW/pages/triplay/images/bg/whats_thisBody.gif" class="displayNone" alt="" />',
	'<img src="/WebGW/pages/triplay/images/bg/whats_thisBottom.gif" class="displayNone" alt="" />',
	'<div class="wtcClose" onclick="closeWhatsThisPopup()"></div>',
	'<p id="whatsThisContent" class="body">',
	'' + textToDisplay + '',
	'</p>',
	'<div class="footer"></div>'].join('');

	var el = Event.element(e);

	if (getElementLeftPosition(el) + 270 > document.documentElement.clientWidth) {
		whatsThisElement.style.left = getElementLeftPosition(el) + el.offsetWidth - 220 + 'px';
	}else{
		whatsThisElement.style.left = getElementLeftPosition(el) + el.offsetWidth - 120 + 'px';
	}

	if(textToDisplay=='edit_a_friend'){
		whatsThisElement.style.top = getElementTopPosition(el) + 'px';
	}else{
		whatsThisElement.style.top = getElementTopPosition(el) +11 + 'px';
	}
    
    Effect.Appear('whatsThisPopup',{duration: .33});
	gWhatsThisShowing = true;
    }

try {
	document.execCommand("BackgroundImageCache", false, true);
} catch(e) {}

/* set document title */
function setTitle(ttl){
	document.title = ttl;
}

/*
	starList- a technuiqe for giving a list/menu items an HOVER psaudo behavior
	plz provide the UL's ID
 */
function setListMouseEvents(menuId){
	function mouseEvent(event){
		if (this.getElementsByTagName('input')[0].checked) return;
		if(!event) event = window.event;
		this.className = (event.type == 'mouseover') ? menuId + 'hover' : '';
	}

	// looping the list scope and giving it RollOverout behaviors
	var LIs = $(menuId).getElementsByTagName('li');
	for (var i = 0, leni=LIs.length; i < leni; i++) {
		LIs[i].onmouseover = mouseEvent;
		LIs[i].onmouseout = mouseEvent;
	}

}

/* decode html entities */
String.prototype.decodeHTMLEntities = function(){
	var str = this;
	var entities = str.match(/&#\d+;?/g);
	if (!entities) return str;
	for(var i=0, decoded, leni=entities.length; i < leni; i++){
		decoded = String.fromCharCode((entities[i]).replace(/\D/g,""));
		str = str.replace(/&#\d+;?/, decoded);
	}
	return str;
}

function getDigitRecipientByRecipientId(digit, recipientId){
	for (var i=0; i < digit.recipients.length; i++){
		if (digit.recipients[i].recipientId == recipientId) return digit.recipients[i];
	}
	return null;
}

/* return the absolute computed position of element */
function getElementPosition(el) {
	el = $(el);
	// has to be part of document to have pageXY
	if ((!el.parentNode || !el.offsetParent || el.getStyle('display') == 'none') && el != document.body) return false;

	var parentNode = null;
	var pos = [];
	var box;

	// IE
	if (el.getBoundingClientRect) {
		box = el.getBoundingClientRect();
		var scrollTop, scrollLeft;
		if (document.documentElement){
			scrollTop = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
			scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
		} else {
			scrollTop = scrollLeft = 0;
		}
		return [box.left + scrollLeft, box.top + scrollTop];
	}
	// safari, opera, & gecko
	else {
		pos = [el.offsetLeft, el.offsetTop];
		parentNode = el.offsetParent;

		// safari: if el is abs or any parent is abs, subtract body offsets
		var hasAbs = el.getStyle('position') == 'absolute';

		if (parentNode != el) {
			while (parentNode) {
				pos[0] += parentNode.offsetLeft;
				pos[1] += parentNode.offsetTop;
				if (Prototype.Browser.WebKit && !hasAbs &&
					parentNode.getStyle('position') == 'absolute') {
					hasAbs = true;
					// we need to offset if any parent is absolutely positioned
				}
				parentNode = parentNode.offsetParent;
			}
		}

		if (Prototype.Browser.WebKit && hasAbs) { //safari doubles in this case
			pos[0] -= el.ownerDocument.body.offsetLeft;
			pos[1] -= el.ownerDocument.body.offsetTop;
		}
	}

	parentNode = el.parentNode;

	// account for any scrolled ancestors
	while (parentNode.tagName && parentNode.tagName.toLowerCase() != 'html'){
		// work around opera inline/table scrollLeft/Top bug
		if (parentNode.getStyle('display').search(/^inline|table-row.*$/i)){
			pos[0] -= parentNode.scrollLeft;
			pos[1] -= parentNode.scrollTop;
		}

		parentNode = parentNode.parentNode;
	}
	return pos;
}

/* toggle box display on/off & set a listener on the body to close it when focusing away */
var gBoxDisplayListener;
function toggleBoxDisplay(evt, boxId, buttonId){
	var box = $(boxId);
	if (box.style.display != 'block'){
		switch (boxId) {
			case 'quick_searchFriends':
				showQuickSearchFriends(false);
				break;
			default:
				displayElement(box);
				break;
		}
		gBoxDisplayListener = toggleBoxDisplay.bindAsEventListener(this, boxId, buttonId);
		$(document.body).observe('click', gBoxDisplayListener);
	} else {
		if (evt) var element = Event.element(evt);
		if (evt && (element.id == buttonId || element.descendantOf(box))) return;
		closeBoxDisplay(boxId);
	}
}
/* close box & stop body listener */
function closeBoxDisplay(boxId){
	switch (boxId) {
		case 'quick_searchFriends':
			showQuickSearchFriends(false);
			break;
		default:
			hideElement(boxId);
			break;
	}
	document.body.stopObserving('click', gBoxDisplayListener);
}

/* Get a string and return it as a series of spans */
function breakString(str, partLen, className) {
	var returnValue = '';
	if ((partLen <= 0) || (partLen == undefined)) partLen = 10; /* Default value */
	if ((className == '') || (className == undefined)) className = floatL; /* Default value */
	// ie6 doesnt break the words as it should. thats why i opened it for all the browsers.
	for (var i=0, leni=Math.ceil(str.length/partLen); i < leni; i++){
		returnValue += '<span class="' + className + '">' + str.substring(i*partLen, (i+1)*partLen) + '</span>';
	}
	return(returnValue);
}

/* Receive a string and return true/false if it contains */
/* a portion that is longer than the limitLength */
function findLongestString(str, limitLength, splitBy) {
	var strParts = str.split(splitBy);
	try {
	for (var i = 0, leni = strParts.length; i < leni; i++) {
		if (strParts[i].length >= limitLength) return true;
	}
	} catch (e) {}
	return false;
}
/* Extend array to enable finding if an object exists or not in the array */
Array.prototype.exists = function (entry) {
	for(var i = 0; i < this.length; i++) {
		if (this[i] == entry) return true;
	}
	return false;
}

/* Get an address we already know is wrong and return the correct */
/* error message */
function anaylzeError(address) {
	var emailPat = new RegExp(/^(.+)@(.+)$/);
	var mobilePat =new RegExp(/^[0-9]*$/);
	var matchArray = address.match(emailPat);

	if (matchArray != null) { // Address is of email type
		return ('<span style="float: left; width: 40%;">' + address + '</span><span style="float: right; width: 60%; text-align: left;">' + TEXT.incorrect_email_address + '</span>');
	} else {
		address = address + '';
		address = address.strip().replace(/-/, '');

		matchArray = address.match(mobilePat);

		if (matchArray != null) { // Address is of numeric type
			return ('<span style="float: left; width: 40%;">' + address + '</span><span style="float: right; width: 60%; text-align: left;">' + TEXT.invalid_number + '</span>');
		} else {
			return ('<span style="float: left; width: 40%;">' + address + '</span><span style="float: right; width: 60%; text-align: left;">' + TEXT.incorrect_format + '</span>'); // Contact is not in user's contact list
		}

		/* NOTE! the full fix should query the server if the last if      */
		/* was reached to verify if the string entered contains a TriPlay */
		/* member name. In that case apparently this member is not a      */
		/* contact of the sending party and a proper error message should */
		/* be added */
	}
}

/* Extract details from URL */
/* This method replaces a server method */
/* It takes in a URL parameter and splits it up */
/* It generates */
function parseLocation(locationString) {
	var parts = locationString.split('/');
	var suffix = parts[parts.length - 1]; /* Obtain the last part of the link */
	var publicAlbumsURLinfo = createPublicAlbumsUrlInfo();
	var innerDetailsParts = null;
	var innerDetails = null;

	// Possible values of locationString
	// http://xxx.triplay.com/username
	// http://xxx.triplay.com/username#albums; 				-> albums
	// http://xxx.triplay.com/username#album;labelId=100 	-> album
	// http://xxx.triplay.com/username#digit;digitId=8a8bd58d17a604bc0117a63790750067&labelId=100 -> digit

	// http://xxx.triplay.com/username			-> albums
	// http://xxx.triplay.com/username/albumId	-> album

	suffix = suffix.toLowerCase();
	if (!suffix.include('#')) {
		switch (parts.length) { // Count the number od shalshes to decide how to parst the location
			case gUrlPartsCountAlbums:	// albums ...
					publicAlbumsURLinfo.albumUrlType = 'albums';
					publicAlbumsURLinfo.username = suffix;
				break;
			case gUrlPartsCountAlbum:
					publicAlbumsURLinfo.albumUrlType = 'album';
					publicAlbumsURLinfo.username = parts[gUrlPartsUsernameIndex];
					publicAlbumsURLinfo.labelId = parts[gUrlPartsLabelIndex];
				break;
		}
	} else {
		parts = suffix.split('#'); // Cut the latest part of the URL, it contains the data we're looking for
		suffix = parts[1]; // Store this data inside the suffix (we do not need the original part anymore)
		publicAlbumsURLinfo.username = parts[0]; // Add the username

		if (suffix.include('album;')) {
			publicAlbumsURLinfo.albumUrlType = 'album';
			innerDetailsParts = suffix.split('='); // Seperate the value from the string
			publicAlbumsURLinfo.labelId = innerDetailsParts[1];
		} else if (suffix.include('digit;')) {
			publicAlbumsURLinfo.albumUrlType = 'digit';
			var labelId = null;
			var digitId = null;

			innerDetailsParts = suffix.split(';'); // Get the digit and album values part first
			innerDetails = innerDetailsParts[1];
			innerDetailsParts = innerDetails.split('&'); // Seperate into to values, digit and album
			labelId = innerDetailsParts[1].split('=');
			digitId = innerDetailsParts[0].split('=');
			publicAlbumsURLinfo.labelId = labelId[1];
			publicAlbumsURLinfo.digitId = digitId[1];
		} else {
			publicAlbumsURLinfo.albumUrlType = 'albums';
		}
	}

	return publicAlbumsURLinfo;
}function ImagePreloader() {
	var arr = $A(arguments);
	var img;
	for (var i = 0, leni = arr.length; i < leni; i++){
		img = new Image();
		img.src = '/WebGW/pages/triplay/images/'+arr[i];
		img.onerror = function(){
			if (console && console.error) console.error('Image not found using ImagePreloader: ' + img.src);
		}
	}
}

/*
function preloadAllImages(){
	ImagePreloader('bg/orangePictureHolder.gif','bg/whats_thisTop.png',
		'bg/whats_thisTop.gif','bg/whats_thisBody.gif','bg/whats_thisBottom.gif','btns/x_box_button.gif','btns/x_box_buttonDown.gif',
		'btns/x_box_buttonOn.gif','bg/orange_folder.jpg','icons/shareFolderByEmailOn.gif','icons/shareFolderByEmailDown.gif','bg/folderMenuLOn.gif',
		"bg/folderMenuLDown.gif","bg/folderMenuMOn.gif","bg/folderMenuMDown.gif","bg/folderMenuMDis.gif",
		"bg/folderMenuROn.gif","bg/folderMenuRDown.gif","bg/folderMenuMOnPrvt.gif","bg/folderMenuMDownPrvt.gif",
		"btns/genericBtns/verySmallLeftOn.gif","btns/genericBtns/verySmallBodyOn.gif","btns/genericBtns/verySmallRightOn.gif",
		"btns/genericBtns/verySmallRightDown.gif","btns/genericBtns/verySmallBodyDown.gif","btns/genericBtns/verySmallLeftDown.gif",
		"btns/genericBtns/smallLeftOn.gif","btns/genericBtns/smallBodyOn.gif","btns/genericBtns/smallRightOn.gif",
		"btns/genericBtns/smallLeftDown.gif","btns/genericBtns/smallBodyDown.gif",
		"btns/genericBtns/smallRightDown.gif","btns/genericBtns/normalBtnLeftOn.gif","btns/genericBtns/normalBtnBodyOn.gif",
		"btns/genericBtns/normalBtnRightOn.gif","btns/genericBtns/normalBtnLeftDown.gif","btns/genericBtns/normalBtnBodyDown.gif",
		"btns/genericBtns/normalBtnRightDown.gif","btns/genericBtns/selectBtnBody_on.gif",
		"btns/genericBtns/selectBtnBody_down.gif","btns/genericBtns/selectBtnLeft_down.gif",
		"btns/genericBtns/selectBtnLeft_on.gif","btns/genericBtns/smallFatBtnDwn.gif",
		"btns/genericBtns/smallFatBtnOn.gif","btns/genericBtns/fatBtnDwn.gif",
		"btns/genericBtns/fatBtnOn.gif","dialogs/smallBtnDown.gif","dialogs/smallBtnOn.gif",
		"btns/genericBtns/shrinkedBtnDwn.gif","btns/genericBtns/shrinkedBtnOn.gif",
		'dialogs/pop_top.gif','dialogs/pop_top_left.gif','dialogs/pop_top_right.gif',
		'dialogs/pop_bottom_right.gif','dialogs/pop_bottom_left.gif','dialogs/pop_bottom.gif','btns/genericBtns/smallRightOn.gif',
		'btns/genericBtns/smallBodyOn.gif','btns/genericBtns/smallLeftOn.gif','btns/genericBtns/smallRight.gif','btns/genericBtns/smallBody.gif',
		'btns/genericBtns/smallRightDown.gif','btns/genericBtns/smallBodyDown.gif','btns/genericBtns/smallLeftDown.gif',
		'lang/de/bg/phoneStatesDialog.gif','lang/en/bg/phoneStatesDialog.gif','dialogs/pop_top.gif','dialogs/pop_top_left.gif',
		'dialogs/pop_top_right.gif','dialogs/pop_bottom.gif','dialogs/pop_bottom_left.gif','dialogs/pop_bottom_right.gif',
		'btns/genericBtns/normalBtnLeft.gif','btns/genericBtns/normalBtnBody.gif','btns/genericBtns/normalBtnRight.gif');
}
*//** === GLOBAL VARIABLES === */

/* TriPlay Application ID */

var triplayApplicationId = 2;

/* dialogs */
var gDialogManager = null;

/* html blocks */
var gHeadBlock = null;
var gNavBlock = null;
var gMainBlock = null;
var gUserBackPackArea = null;
var gPublicUserBackpackArea = null;
var gComponentsBlock;
var gContactsBlock = null;
var gMessageComposer = null;
var gNotification = null;
var gPlaylistPlayer = null;
var gMoveToFolder_Panel = null;
var gIsImagePreloader = null;

/* global data holders */
var gStorageInfo = null;
var gAlbumId = null;
var gArrSelectedDigits = [];
var gDigitId = null;
var gPrevDigitId = null;
var gNextDigitId = null;

var gFilterContactsOpen = false;
var gUserState = null;
var gPublicState = 'notLoggedIn';
var gIsLoggedIn = false;
var gLocation = null;
var gRecipients = [];
var gPublicAlbumsUrlInfo = null; // albumdUrlType, digitId, labelId, userName
var gCaptionEditorShowing = false;
/*var gDigitsAlbumsMap = null;*/
var gAvatar = null;
var gSingleImg = null;
var gMobileAlerts = null;
var gPublicAlbumTO = null;
var gPublicAlbumUsername = null;
var gNickname = null;

var RecipientTO = function(recipientId, requestedAddress, recipientType) {
    this.recipientId = recipientId;
    this.requestedAddress = requestedAddress;
    this.recipientType = recipientType;
}

var gUser = {
    /*statusType: 0,*/
    userId: 0,
    username: "",
    nickname: "",
    billingKey: ""
    /*msisdn: ""*/
};

var gPublicUser = {
    username: "",
    nickname: ""
};

/* file upload vars */
var gSelectedBlock = null;
var gFromSelect = null;

/* page navigation */
var gAlbumsSortBy = "CREATION_TIME"; // init global Albums Sort by
var gAlbumSortDir = "DESC";
var gDigitsSortBy = "RECEIVED_TIME"; // init global Pictures Sort by
var gDigitSortDir = "DESC";
var gEditDigit = null;
var gCropDigit = null;

var gHistoryFlag = false;

/* digit menu */
var gDigitMenu = null;	// digit menu object
var gDigitSortMenu = null;	// sort digits menu object
var gMoveToFolderMenu;
gMoveToFolderMenu = null;	// move to folder menu object
var gMoreSingleMediaMenu = null;	// more action menu in single media dialog
var gMouseX = 0;	// mouse x position
var gMouseY = 0;	// mouse y position
var gOverDigit = null; // this var required to fix IE behavior
var gChangeRecipientMenu = null;

/* drag & drop */
var gDragging = false;
var gAttachmentType = null;
var gAttachmentAlbumId = null;
var gAttachmentDigitId = null;

var gFolder2Upload = null;
var gClickedThumb = null;
var gReceivedDigitsToShow = 7;
var gMusicPreviewDigitsToShow = 5;
var gFolderFeedbackMessage = null;

/** ============================ */
/** === PAGE LOAD FUNCTIONS === */
/** ========================== */

/* page init - logged in */
function initPage() {
    gPublicState = 'loggedIn';
    gIsLoggedIn = true;
    gLoader.createLoader();

    gDialogManager = new DialogManager();

    CM.sendRequest('getTriplayLoginResponse$AP');

}

function initPageAfterCallback() {
    CM.sendRequest('getUserStorageInfo$AP');
    CM.sendRequest('getUserContactsTOs$AP', 'ALL');
    CM.sendRequest('getUserCommunicationAddressTOs$AP');
    CM.sendRequest('resendPrivilegeRequestToSelf$AP');
    CM.sendRequest('getSubscriptionPackageData', triplayApplicationId); // Get user's credits

    dhtmlHistory.initialize();
    dhtmlHistory.addListener(handleHistoryChange);

    var hd = getHistoryData(dhtmlHistory.getCurrentLocation());
    var q = createAlbumsQuery();

    if (gUserState != "PUBLIC") {
        switch (hd.context) {
            case "albums":
                CM.sendRequest('getUserAlbums$renderAlbumsListPage', q);
                break;
            case "album":
                CM.sendRequest('getUserAlbums$FirstLoadUserAlbums', q);
                break;
            case "digit":
                CM.sendRequest('getUserAlbums$FirstLoadDigits', q);
                break;
            default:
                CM.sendRequest('getUserAlbums$renderAlbumsListPage', q);
        }
    }

    gHistoryFlag = true;
}

/* get user country code */
var gCountryCode = null;
// Country list
// Andorra (376), Argentina (54), Belgium (32), Bosnia-Herzegovina (387), Brazil (55), Chile (56), Croatia (385), Czech Republic (420), France (33), Faroe Islands (298), Finland (358), France (33),
// Germany (49), Gibraltar (350), Hungary (36), Ireland (353), Israel (972), Italy (39), Mexico (52), Norway (47), Spain (34), Poland (48), Portugal (351), Romania (40),
// Serbia (381), Slovakia (421), Slovenia (386), Switzerland (41), The Netherlands (31), Turkey (90),Ukraine (380) , United Kingdom (44), United States (1)
var gCountryCodeArr = new Array('376', '54', '32', '387', '55', '56', '385', '420', '33', '298', '358', '33', '49', '350', '36', '353', '972', '39', '52', '47', '34', '48', '351', '40', '381', '421', '386', '41', '31', '90', '44', '1', '380');

function getUserCountryCode() {
    if (gUser.userTO.primaryCommunicationAddress.operator) gCountryCode = gUser.userTO.primaryCommunicationAddress.operator.country.phonePrefix;
    if (gCountryCode) return;
    for (var i = 0; i < gCountryCodeArr.length; i++) {
        if (gCountryCodeArr[i] == gUser.userTO.primaryCommunicationAddress.communicationAddress.substring(0, gCountryCodeArr[i].length)) {
            gCountryCode = parseInt(gCountryCodeArr[i]);
        }
    }
}
/* render the albums list page - callback for getUserAlbums$renderAlbumsListPage */
function renderAlbumsListPage(albumsList) {
    findMusicPlaylistAlbum(albumsList);
    gAlbumId = null;
    if (albumsList) {
        gDigitsCacheManager.addAlbums(albumsList, 'FOLDER', false);
    }

    // render the page parts
    createReceivedAlbumInCache();
    /* Bug fix, ensure that all the received files are reterived, the filtering is done inside the template */
    gDigitsCacheManager.getDigits(gSystemLabels.RECENTLY_RECEIVED, 1, 999, 'cacheDigits$renderRecentlyRecived');
    gDigitsCacheManager.getDigits(gSystemLabels.GREETINGS, 1, 999, 'cacheDigits$renderGreetings');
    gDigitsCacheManager.getDigits(gSystemLabels.PLAYLIST, 1, gMusicPreviewDigitsToShow, 'cacheDigits$renderMusicPreview');

    gNavBlock = TM.loadAndParse('nav_albums_list.html', null, 'navBlock');
    gMainBlock = TM.loadAndParse('main_albums_list.html', null, 'mainBlock');
    try {
        if (!gNotification) gNotification = TM.loadAndParse('notifications.html', null, 'notificationBox');
        notificationsCheck();
    } catch (ex) {
    }

    setFolderDraggables();
    setZoneDraggables();
    dhtmlHistory.add("albums;");
}

/* callback for cacheDigits$renderRecentlyRecived */
function renderRecentlyRecived(digitsList) {
    if (gAlbumId == null) {
        gComponentsBlock = TM.loadAndParse('recently_received.html', null, 'recently_received');
    }
}

/* callback for cacheDigits$renderRecentlyRecived */
function renderGreetings(digitsList) {
    if (gAlbumId == null) {
        gComponentsBlock = TM.loadAndParse('greetings.html', null, 'greetings');
    }
}

/* callback for cacheDigits$renderMusicPreview */
function renderMusicPreview(digitsList) {
    gComponentsBlock = TM.loadAndParse('music_preview.html', null, 'music_preview');
}

/* create received album object for cache */
function createReceivedAlbumInCache() {
    var receivedMediaAlbum = {albumTOList:[{
        id:gSystemLabels.RECENTLY_RECEIVED,
        numMedia:'unknown',
        name : TEXT.received_media,
        shareLevel : 'PRIVATE'
    }]};
    gDigitsCacheManager.addAlbums(receivedMediaAlbum, 'RECENTLY_RECEIVED', false);
}

/* create received album object for cache */
function createGreetingsAlbumInCache() {
    var receivedMediaAlbum = {albumTOList:[{
        id:gSystemLabels.GREETINGS,
        numMedia:'unknown',
        name : TEXT.received_media,
        shareLevel : 'PUBLIC'
    }]};
    gDigitsCacheManager.addAlbums(receivedMediaAlbum, 'RECENTLY_RECEIVED', false);
}


/* callback for getUserAlbums$FirstLoadUserAlbums - called after page refreshed on album page */
function getFirstLoadUserAlbums(albumsList) {
    findMusicPlaylistAlbum(albumsList);
    var hd = getHistoryData(dhtmlHistory.getCurrentLocation());
    var params = hd.params;

    gDigitsCacheManager.addAlbums(albumsList, 'FOLDER', false);
    createReceivedAlbumInCache();
    createGreetingsAlbumInCache();

    var albumId = $N(params["labelId"]);
    initAlbumPage(albumId);
}

/* init album page */
function initAlbumPage(albumId) {
    if (gDragging) return;
    gAlbumId = albumId;
    gArrSelectedDigits = [];

    if (albumId == gSystemLabels.PLAYLIST) {
        gDigitsCacheManager.getDigits(albumId, 1, gDigitsCache[albumId].album.numMedia, 'cacheDigits$showMusicAlbum');
    } else {
        gDigitsCacheManager.getDigits(albumId, 1, gDigitsCache[albumId].album.numMedia, 'cacheDigits$renderAlbumPage');
    }
    dhtmlHistory.add("album;labelId=" + albumId);
}

/* callback for getDigits - render the album page */
function renderAlbumPage() {
    gDigitId = null;
    gCaptionEditorShowing = false;
    document.documentElement.scrollTop = 0;

    // render the page parts
    $I('greetings', '');
    $I('recently_received', '');
    $I('music_preview', '');
    gNavBlock = TM.loadAndParse('nav_album_pics.html', null, 'navBlock');
    gMainBlock = TM.loadAndParse('main_album_pics.html', null, 'mainBlock');
    if (!gNotification) {
        gNotification = TM.loadAndParse('notifications.html', null, 'notificationBox');
        notificationsCheck();
    }

    createDigitMenu();
    createDigitSortMenu();
    createMoreSingleMediaMenu();
    createMoveToFolderMenu();
    addDigitEventListeners();
    addMoveToFolderListeners('toasterMoveToFolder');
    /* Bug 3104 fix, enable drag drop on all folder types, including private folders */
    /* AUDIO files will be blocked by existing code. Private folder is not draggable */
    /* as a folder */
    setDigitDraggables();
    /* if (gDigitsCache[gAlbumId].album.shareLevel != "PRIVATE") setDigitDraggables(); */
    setZoneDraggables();

    // if there's a folder feedback message pending - set it
    if (gFolderFeedbackMessage) {
        setFeedbackMessage.apply(this, gFolderFeedbackMessage);
        gFolderFeedbackMessage = null;
    }
}

/* show music album */
function showMusicAlbum() {
    gDigitId = null;
    gCaptionEditorShowing = false;

    // render the page parts
    $I('recently_received', '');
    $I('music_preview', '');
    $I('greetings', '');
    gNavBlock = TM.loadAndParse('nav_music_album.html', null, 'navBlock');
    gMainBlock = TM.loadAndParse('main_music_album.html', null, 'mainBlock');
    if (!gNotification) {
        gNotification = TM.loadAndParse('notifications.html', null, 'notificationBox');
        notificationsCheck();
    }

    createMoveToFolderMenu();
    addMoveToFolderListeners('playlistMoveToFolder');
    setZoneDraggables();
}

/* refresh album page */
function refreshAlbumPage() {
    CM.sendRequest('getUserAlbums$refreshAlbumDigitsList', createAlbumsQuery());
}

/* callback for getUserAlbums$refreshAlbumDigitsList - refresh album digit list */
function refreshAlbumDigitsList(albumsList) {
    findMusicPlaylistAlbum(albumsList);
    if (albumsList) gDigitsCacheManager.addAlbums(albumsList, 'FOLDER', false);
    gDigitsCacheManager.getDigits(gAlbumId, 1, gDigitsCache[gAlbumId].album.numMedia, 'cacheDigits$renderAlbumPage');
}

/* callback for getUserAlbums$FirstLoadDigits - sets albums after page refreshed on digit dialog */
function getFirstLoadDigits(albumsList) {
    findMusicPlaylistAlbum(albumsList);
    var hd = getHistoryData(dhtmlHistory.getCurrentLocation());
    var context = hd.context;
    var params = hd.params;
    if (albumsList) gDigitsCacheManager.addAlbums(albumsList, 'FOLDER', false);
    createReceivedAlbumInCache();

    gAlbumId = $N(params["labelId"]);
    gDigitId = $N(params["digitId"]);
    gDigitsCacheManager.getDigits(gAlbumId, 1, gDigitsCache[gAlbumId].album.numMedia, 'cacheDigits$getFirstLoadDigit');
}

/* callback for getDigits - sets digits after page refreshed on digit dialog */
function getFirstLoadDigit(digitList) {
    var hd = getHistoryData(dhtmlHistory.getCurrentLocation());
    var params = hd.params;

    renderAlbumPage(digitList);
    gDigitId = $N(params["digitId"]);
    openDialog('edit_media.html', null, 682, backToAlbum, true, 'screen', false, true);
    // add event listeners for move to folder button
    addEditMoveToFolderListeners();
    addMoveToFolderListeners('toasterMoveToFolder');
}

/* find id of music album */
function findMusicPlaylistAlbum(albumsList) {
    if (!albumsList) return;
    for (var k = 0, lenk = albumsList.albumTOList.length; k < lenk; k++) {
        if (albumsList.albumTOList[k].labelType == 'MUSIC_PLAYLIST') {
            gSystemLabels.PLAYLIST = albumsList.albumTOList[k].id;
            return;
        }
    }
    gSystemLabels.PLAYLIST = null;	// if not found a music playlist album
}
/* check if it's user first login directly from registration */
function receivedFirstTime() {
    return (location.href.indexOf('firstrun') != -1);
}

function checkIfUserAuthorizedForService() {
    
}

/** =================================== */
/** === PUBLIC PAGE LOAD FUNCTIONS === */
/** ================================= */
/* init public page */
function initPublicPage() {
    CM.sendRequest('getTriplayLoginResponse$AP');
    gLoader.createLoader();
    writeUIModeToCookie();

    gLocation = window.location.href;
    if (gLocation.include('?')) gLocation = gLocation.substring(0, gLocation.indexOf('?'));
    gPublicAlbumsUrlInfo = parseLocation(gLocation);

    var publicAlbumsQuery = createPublicAlbumsQuery();
    CM.sendRequest('getPublicUserProfile$AP', publicAlbumsQuery, gPublicAlbumsUrlInfo.username);

    //	if (gIsLoggedIn){
    //		CM.sendRequest('getUserContactsTOs$AP', 'ALL');
    //		CM.sendRequest('getUserCommunicationAddressTOs$AP');
    //		keepAlive();
    //	}
    gDialogManager = new DialogManager();
}

/* callback for getPublicUserProfile$AP */
function setPublicUserProfile(webPublicUserProfile) {
    if (!webPublicUserProfile) {
        location.href = 'http://' + gAPP + '/WebGW/pages/triplay/404.html?mode=0';
        return;
    }

    dhtmlHistory.initialize();
    dhtmlHistory.addListener(handleHistoryChange);

    var hd = getHistoryData(dhtmlHistory.getCurrentLocation());
    var context = hd.context;
    var params = hd.params;
    var publicAlbumsQuery = createPublicAlbumsQuery();
    gPublicUser.username = webPublicUserProfile.username;
    gPublicUser.nickname = webPublicUserProfile.nickname;
    if (!gHeadBlock && ((gIsLoggedIn && gUser.username) || !gIsLoggedIn)) gHeadBlock = TM.loadAndParse('head_public_pane.html', null, 'headBlock');
    gPublicUserBackpackArea = TM.loadAndParse('userPublicBackpackArea.html', null, 'userPaublicBackPackArea');

    switch (gPublicAlbumsUrlInfo.albumUrlType) {
        case "albums":
            //CM.sendRequest('getPublicAlbums$renderPublicAlbumsList', publicAlbumsQuery, gPublicUser.username);
            renderPublicAlbumsList(webPublicUserProfile.albums);
            break;
        case "album":
            //CM.sendRequest('getPublicAlbums$FirstLoadPublicAlbums', publicAlbumsQuery, gPublicUser.username);
            getFirstLoadPublicAlbums(webPublicUserProfile.albums);
            break;
        case "digit":
            //CM.sendRequest('getPublicAlbums$FirstLoadPublicDigits', publicAlbumsQuery, gPublicUser.username);
            getFirstLoadPublicAlbums(webPublicUserProfile.albums);
            break;
        default:
            handlePublicAlbumsUrl(webPublicUserProfile.albums);
    }
    gHistoryFlag = true;
    if (!gIsImagePreloader) {
        preloadAllImages();
        gIsImagePreloader = true;
    }
}

/* callback for getPublicAlbums$renderPublicAlbumsList */
function renderPublicAlbumsList(albumsList) {
    if (albumsList) {
        gDigitsCacheManager.addAlbums(albumsList, 'FOLDER', false);
    }
    gAlbumId = null;
    gMainBlock = TM.loadAndParse('main_public_albums_list.html', null, 'mainBlock');
    dhtmlHistory.add("albums;");
    if (!gIsImagePreloader) {
        preloadAllImages();
        gIsImagePreloader = true;
    }
}

/* callback for getPublicAlbums$FirstLoadPublicAlbums */
function getFirstLoadPublicAlbums(albumsList) {
    var hd = getHistoryData(dhtmlHistory.getCurrentLocation());
    var params = hd.params;

    if (albumsList) gDigitsCacheManager.addAlbums(albumsList, 'FOLDER', false);
    var albumId = (params["labelId"] != undefined ? $N(params["labelId"]) : gPublicAlbumsUrlInfo.labelId);
    initPublicAlbumPage(albumId);
}

/* callback for getPublicAlbums$FirstLoadPublicDigits */
function getFirstLoadPublicDigits(albumsList) {
    var hd = getHistoryData(dhtmlHistory.getCurrentLocation());
    var context = hd.context;
    var params = hd.params;
    if (albumsList) gDigitsCacheManager.addAlbums(albumsList, 'FOLDER', false);

    gAlbumId = $N(params["labelId"]);
    gDigitsCacheManager.getDigits(gAlbumId, 1, gDigitsCache[gAlbumId].album.numMedia, 'cacheDigits$getFirstLoadPublicDigit');
}

/* In order to enable correct view of public shared album sent from another user */
/* we need to extract some details about a specific album, extract all it's public */
/* albums and then choose the album we need */
function getPublicAlbumsTO(username, context) {
    var publicAlbumsQuery = createPublicAlbumsQuery();
    switch (context) {
        case 'forward':
            CM.sendRequest('getPublicAlbums$getPublicAlbumAsAttachment', publicAlbumsQuery, username);
            break;
        case 'activityMonitor' :
            CM.sendRequest('getPublicAlbums$amExtractAlbumTO', publicAlbumsQuery, username);
            break;
        case 'messages':
            CM.sendRequest('getPublicAlbums$extractAlbumTO', publicAlbumsQuery, username);
            break;
    }
}

/* callback getPublicAlbums$extractAlbumTO */
function extractAlbumTO(albumsList) {
    var albumTO = getAlbumTOFromList(albumsList);

    TM.loadAndParse('p_message_view.html', {digit:gPublicAlbumDigit, album:albumTO}, 'messageViewContainer');
    setViewMessageFocused(gPublicAlbumTblObj, gPublicAlbumTabId, gPublicAlbumDigitId);
}

function amExtractAlbumTO(albumsList) {
    gPublicAlbumTO = getAlbumTOFromList(albumsList);
    beforeSwitchToPublicPage();
}

function getAlbumTOFromList(albumsList) {
    var albumTO = null;
    // lookup the specific public album
    for (var i = 0, leni = albumsList.albumTOList.length; i < leni; i++) {
        if (albumsList.albumTOList[i].id == gPublicAlbumId) {
            albumTO = albumsList.albumTOList[i];
            break;
        }
    }
    return (albumTO);
}

/* callback for getDigits */
function getFirstLoadPublicDigit() {
    var hd = getHistoryData(dhtmlHistory.getCurrentLocation());
    var params = hd.params;

    if (gAlbumId) {
        gDigitId = $N(params["digitId"]);
    } else {
        gDigitId = null;
    }
    renderPublicDigitPage();
}

/* callback for getPublicAlbums$handlePublicAlbumsUrl */
function handlePublicAlbumsUrl(albumsList) {
    if (albumsList) gDigitsCacheManager.addAlbums(albumsList, 'FOLDER', false);
    switch (gPublicAlbumsUrlInfo.albumUrlType) {
        case "ALBUMS":
            renderPublicAlbumsList(albumsList);
            break;
        case "SPECIFIC_ALBUM":
            initPublicAlbumPage(gPublicAlbumsUrlInfo.labelId);
            break;
        case "DIGIT":
            initPublicAlbumPage(gPublicAlbumsUrlInfo.labelId, 'cacheDigits$renderPublicDigitPage');
            break;
    }
}

/* init public album page */
function initPublicAlbumPage(albumId, method) {
    gDigitsSortBy = "RECEIVED_TIME";
    gDigitSortDir = "DESC";
    gAlbumId = albumId;
    if (!method) method = 'cacheDigits$renderPublicAlbumPage';
    try {    // Bug #3309
        // Ensure that the album Id is still valid, this is the fastest way, may not be the fastest solution
        gDigitsCacheManager.getDigits(gAlbumId, 1, gDigitsCache[gAlbumId].album.numMedia, method);
        dhtmlHistory.add("album;labelId=" + gAlbumId);
        if (!gIsImagePreloader) {
            preloadAllImages();
            gIsImagePreloader = true;
        }
    } catch (e) {
        location.href = 'http://' + gAPP + '/WebGW/pages/triplay/404.html?mode=1';
    }
}

/* callback for getDigits */
function renderPublicAlbumPage() {
    gDigitId = null;
    // render the page parts
    if (!gHeadBlock) gHeadBlock = TM.loadAndParse('head_public_pane.html', null, 'headBlock');
    gMainBlock = TM.loadAndParse('main_public_album_pics.html', null, 'mainBlock');
    if (!gIsImagePreloader) {
        preloadAllImages();
        gIsImagePreloader = true;
    }
}

function renderPublicDigitPage() {
    renderPublicAlbumPage();
    openPublicMedia(gPublicAlbumsUrlInfo.digitId);
    if (!gIsImagePreloader) {
        preloadAllImages();
        gIsImagePreloader = true;
    }
}

/** ======================= */
/** === USER & STORAGE === */
/** ===================== */
/* callback for getTriplayLoginResponse$AP */
function updateLoginResponse(triplayWebLoginResponse) {
    if (triplayWebLoginResponse == null) {
        gPublicState = 'notLoggedIn';
        gIsLoggedIn = false;
        return; // Skip the rest of the method if the response is null
    }
    initPageAfterCallback();
    gPublicState = 'loggedIn';
    gIsLoggedIn = true;
    if (gUserState == 'PUBLIC') {
        CM.sendRequest('getUserContactsTOs$AP', 'ALL');
        CM.sendRequest('getUserCommunicationAddressTOs$AP');
        keepAlive();
    }
    if (triplayWebLoginResponse) gUser = triplayWebLoginResponse; // username, nickname, userId

    notificationsCheck();
    /* Force notification timer to start */
    if (!gHeadBlock) {
        if (gUserState == 'PRIVATE') {
            gHeadBlock = TM.loadAndParse('head_pane.html', null, 'headBlock');
            gUserBackPackArea = TM.loadAndParse('userBackpackArea.html', null, 'userBackPackArea');
            // check presenc
            if (gUser.userTO.receiveNotificationsOnMobile === false) {
                gDataCookie.presence = 'Online';
                gDataCookie.settingsPresence = 'Never';
            } else {
                getUIModeFromCookie();
                // If not set or cookie set to Never while server has changed, set to default state
                if (!gDataCookie.presence || gDataCookie.presence == 'Never' || gDataCookie.presence == '')
                    gDataCookie.presence = 'Always';
            }

            writeUIModeToCookie();
            setPresenceFromCookie();
        } else if (gIsLoggedIn && gPublicUser.nickname) {
            gHeadBlock = TM.loadAndParse('head_public_pane.html', null, 'headBlock');
        }
    }
    getUserCountryCode();
    // if already got contacts from dwr
    if (gUserCommunicationAddresses && gUserContactTOs) {
        createContactsList(renderMessagesColumn);
    }
}

/* callback for getUserStorageInfo$AP */
function updateUserStorageInfo(storageInfo) {
    if (storageInfo) gStorageInfo = storageInfo;
    if (!gStorageInfo || !$("progressMeter")) return;	// if head block not yet parsed

    var percentUsed = getPercentUsed();
    if (percentUsed > 100) percentUsed = 100;
    var totalQuota = getTotalQuota();
    //$("progressMeter").innerHTML = percentUsed + "% of " + totalQuota + "GB";
    $("progressMeter").innerHTML = percentUsed + "%";
    $("progressPrecentImg").style.width = percentUsed + "%";
}
function getPercentUsed() {
    if (!gStorageInfo) return 0;
    return Math.ceil((gStorageInfo.currentUsage / gStorageInfo.totalQuota) * 100);
}
function getTotalQuota() {
    if (!gStorageInfo) return 0;
    return (Math.ceil((gStorageInfo.totalQuota / Math.pow(2, 30)) * 10) / 10);
}

/* =========================== */
/* === LOCATION FUNCTIONS === */
/* ========================= */

/* logout */
function beforeLogout() {
    /*gDataCookie.presence = 'Always';
     writeUIModeToCookie();
     CM.sendRequest('setPresenceState$logout', gPresenceStateClassEnum.Always, TransactionId.next());
     */

    logout();
}
function logout() {
    //	we use 'rurl' var to define to which url the server shouls redirect after the procedure.
    // we also escaped the string.
    if (getL18NModeFromCookie('lang') == 'de') {
        window.location.href = gAlbumspath + "triplay/logout?rurl=http://" + gWWW + "/indexDe.php";
    } else {
        window.location.href = gAlbumspath + "triplay/logout?rurl=http://" + gWWW + "?logout=1";
    }
}

/* get public page url */
function getPublicPageUrl(username, albumId) {
    if (!username) {
        username = gUser.username ? gUser.username : gPublicUser.username ? gPublicUser.username : '';
    }
    if (!username) {
        return '';
    }

    if ((albumId == 'null') || (albumId == null) || (albumId == undefined)) {
        albumId = '';
    } else {
        albumId = '/' + albumId;
    }
    return "/" + username + albumId;
}

/* switch to public page */
function switchToPublicPage(username, albumId, isFromHome, showLogin) {

    gPublicAlbumIsFromHome = isFromHome;
    gPublicAlbumShowLogin = showLogin;
    gPublicAlbumId = albumId;
    gPublicAlbumUsername = username;

    getPublicAlbumsTO(username, 'activityMonitor');
}

/* before switching to public page */
function beforeSwitchToPublicPage() {
    gHeadBlock = null;
    var url = getPublicPageUrl(gPublicAlbumUsername, gPublicAlbumId);
    if (!url) {
        //url = location.href = 'http://' + location.host + '/WebGW/pages/triplay/404.html?mode=1';
        openDialog('p_error.html', {error:TEXT.folder_no_longer_shared, showButton:true, buttonText:TEXT.ok}, 303, null, null, null, null, null, $('messagePreview'), 20, 0);
    } else {
        var rand = Math.random().toString().substring(2);
        url += '?rand=' + rand;
        if (gPublicAlbumShowLogin) url += '&showLogin=1';
    }

    if (gPublicAlbumIsFromHome) {
        window.open(url, "_blank");
    } else {
        window.location.href = url;
    }

    gPublicAlbumIsFromHome = null;
    gPublicAlbumShowLogin = null;
    gPublicAlbumId = null;
    gPublicAlbumUsername = null;
}

/* switch to private page */
function switchToPrivatePage() {
    gHeadBlock = null;
    doSetRedirectURL();
}

/* callback for setRedirectURL$AP */
function doSetRedirectURL() {
    window.location.href = getBaseUrl() + "/home";
}

/* goto register page */
function gotoRegister() {
    window.location.href = getBaseUrl() + "/register";
}

/* get digit url */
function getDigitUrl(digit) {
    var url = getBaseUrl();
    if (url.indexOf("/triplay") != -1) url = url.replace(/\/triplay/, "");
    if ((digit.mediaType == "AUDIO") || (digit.mediaType == "VIDEO")) {
        return (url + "/getImage?mediaLocation=" + digit.storageLocation + "&sizeTemplate=DigitOriginalSize&mediaRadiusAngle=" + digit.rotationDegrees + "&digitId=" + digit.digitId);
    } else {
        return (url + "/getImage?mediaLocation=" + digit.storageLocation + "&sizeTemplate=DigitFullSize&mediaRadiusAngle=" + digit.rotationDegrees);
    }
}

/* get digit embed */
function getDigitEmbed(digit) {
    var embedCode = "";
    if ((digit.mediaType == "AUDIO") || (digit.mediaType == "VIDEO")) {
        embedCode = "<object classid='CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6' width='400' height='300'><param name='url' value='" + getDigitUrl(digit) + "'><param name='uiMode' value='full'><param name='autoStart' value='true'><param name='loop' value='1'><param name='playCount' value='1'><embed src='" + getDigitUrl(digit) + "' width='400' height='300' autostart='1' playcount='1' loop='1' type='application/x-mplayer2' pluginspage='http://microsoft.com/windows/mediaplayer/en/download/' showcontrols='1' uimode='full' name='mediaplayer'></embed></object>"
    } else {
        embedCode = "<img src='" + getDigitUrl(digit) + "' alt='' />";
    }
    return embedCode;
}

/* ========================= */
/* === DIALOG FUNCTIONS === */
/* ======================= */
/* simple dialog open - when template parsing not needed */
function openDialogSimple(templateName, width, callback, hasClose, mask, draggable) {
    openDialog(templateName, null, width, callback, hasClose, mask, true, draggable);
}
/* general dialog open. All params except templateName & obj have default values
 Mask Params are: none, clear, screen */
function openDialog(templateName, obj, width, callback, hasClose, mask, simple, draggable, relativeContainer, offsetX, offsetY) {
    if (obj) obj = eval(obj);
    if (!width) width = DialogManager.prototype.defultWidth; // width defaults to defultWidth
    if (!callback) callback = null; // callback defaults to true
    if (!hasClose) hasClose = true; // hasClose defaults to true
    if (!mask) {
        var parentDialog = Dialog.prototype.openedDialogs[Dialog.prototype.currentInstance];
        if (parentDialog && parentDialog.pageMaskerClass) {
            mask = DialogManager.prototype.getPageMaskName(parentDialog.pageMaskerClass);
        } else {
            mask = 'clear'; // mask defaults to 'clear'
        }
    }

    // hide music player if it is showing
    var playlistPlayer = $('playlistPlayer');
    if (playlistPlayer && playlistPlayer.getStyle('display') == 'block') {
        $('playlistPlayer').style.visibility = 'hidden';
    }

    if (!draggable) draggable = false; // draggable defaults to false
    var html;
    if (simple) {
        html = TM.loadSyncd(templateName);
    } else {
        html = TM.loadAndParse(templateName, obj);
    }
    if (html != "") {
        if (!simple) {
            var editPicImgObj = $("editPicImg");
            if (editPicImgObj) editPicImgObj.style.visibility = "hidden";
        }
        gDialogManager.show(html, width, mask, callback, hasClose, draggable, relativeContainer, offsetX, offsetY);
    }
}

/* close current showing dialog */
function closeDialog() {
    var dialog = Dialog.prototype.openedDialogs[Dialog.prototype.currentInstance];
    if (dialog) {
        if (Dialog.prototype.currentInstance > 0 && Dialog.prototype.openedDialogs.length < 3) {
            var editPicImgObj = $("editPicImg");
            if (editPicImgObj) editPicImgObj.style.visibility = "inherit";
            var dialog1Holder = $('dialog1Holder');
            if (dialog1Holder) dialog1Holder.setOpacity(0.99999); // fix a bug where opacity get stuck when browsing digits
        }
        dialog.close();
    }
    var playlistPlayer = $('playlistPlayer');
    if (playlistPlayer && playlistPlayer.getStyle('display') == 'block' && playlistPlayer.style.visibility == 'hidden' && Dialog.prototype.openedDialogs.length == 0) {
        playlistPlayer.style.visibility = 'visible';
    }
}
/* close main and sub dialogs */
function closeAllDialogs() {
    var openedDialogs = Dialog.prototype.openedDialogs;
    for (var i = openedDialogs.length - 1; i >= 0; i--) {
        if (Dialog.prototype.currentInstance > 0) {
            var editPicImgObj = $("editPicImg");
            if (editPicImgObj) editPicImgObj.style.visibility = "inherit";
        }
        Dialog.prototype.openedDialogs[i].close();
    }
}

function closeEditFriend() {
    if ($('whatsThisPopup')) Effect.Fade('whatsThisPopup', {duration: .25});
}


function closeDialogAndFocus(focusOnObject) {
    closeDialog();
    if ((focusOnObject == undefined) || (!focusOnObject) || (focusOnObject == '')) return;
    makeElBlink(focusOnObject);
    $(focusOnObject).focus();
}

/* open upload dialog */
function openUpload() {
    var album = gDigitsCache[gAlbumId].album;
    openDialog('p_upload_new.html', album, 447);
    gUploadTotal = 0;
}

function openGetFiles() {
    openDialog('p_upload_3rd_party.html', null, 700);
    createSlider('chooseAfolder2Upload', 'cfuSliderTrack', 'cfuSliderHandle')
}
function openGlobalUpload() {
    openDialog('p_upload_new_fromHp.html', null, 460);
    createSlider('chooseAfolder2Upload', 'cfuSliderTrack', 'cfuSliderHandle')
}

/* Bug 3431 fix, ensure that globals are nullified after dialog is closed */
function closeGlobalUpload() {
    if (gClickedThumb) gClickedThumb = null;
    if (gFolder2Upload) gFolder2Upload = null;
    closeDialog();
}

/* open media dialog */
function openMedia(event, digitId) {
    if (gDragging) return;
    if (typeof digitId != 'undefined') gDigitId = digitId;
    if (event && event.ctrlKey) {
        if (gArrSelectedDigits.include(gDigitId)) {
            gArrSelectedDigits = gArrSelectedDigits.without(gDigitId);
        } else {
            gArrSelectedDigits.push(gDigitId);
        }
        // display toaster
        if (gArrSelectedDigits.length > 0) {
            if ($('moveToFolder_Panel').style.display != '') {
                displayElement('moveToFolder_Panel')
                //Effect.BlindDown('moveToFolder_Panel', {duration:.66});
            }
        } else {
            hideElement('moveToFolder_Panel');
        }
    } else {
        // hide digit menu
        instantHideDigitMenu();
        cancelMultipleSelection();
        changeStyle($('digit_' + gDigitId), 'single_picture');
        gOverDigit = null;

        if (gDigitsCache[gAlbumId].album.numMedia > 0) {
            openDialog('edit_media.html', null, 682, backToAlbum, true, 'screen', false, true);
            dhtmlHistory.add("digit;digitId=" + gDigitId + "&labelId=" + gAlbumId);
        } else {
            openDialogSimple('p_edit_no_media.html');
        }
        // add event listeners for move to folder button
        addEditMoveToFolderListeners();
    }
}

/* set loaded digit */
function setLoadedDigit(el, img) {
    if (el && img) {
        $(el).src = img.src;
        $("editPicImg").observe("mouseover", displayDigitControls, false);
        $("editPicImg").observe("mouseout", hideDigitControls, false);
    }
    Dialog.prototype.centerDialog();
}

function setLoadedAvatar() {
    $("avatar_image").src = gAvatar.src;
}

/* callback for open media dialog */
function backToAlbum() {
    removeMediaPlayer();
    dhtmlHistory.add("album;labelId=" + gAlbumId);
}
/* callback for open media dialog */
function backToAlbumsList() {
    removeMediaPlayer();
    renderAlbumsListPage();
}

/* remove media player */
function removeMediaPlayer() {
    var editPicImg = $('editPicImg');
    if (editPicImg && editPicImg.getElementsByTagName('img').length > 0) return; // if regular image and not media player - leave it alone.
    var mediaplayer = $('mediaplayer');
    if (mediaplayer) {
        if (mediaplayer.DoStop) {
            mediaplayer.DoStop();
        } else {
            try {
                editPicImg.innerHTML = '';
            } catch(e) {
            }
        }
    }
}

/* open delete digit */
function openDeleteDigit() {
    instantHideDigitMenu();
    openDialog('p_delete.html', null, 414);
}

/* open delete multiple digits */
function openDeleteMultipleDigits() {
    if (gArrSelectedDigits.length > 0) {
        openDialog('p_delete_multiple.html', gArrSelectedDigits, 414);
    } else {
        openDialog('p_delete_no_selected.html', null, 414);
    }
}

/* open public media dialog */
function openPublicMedia(digitId) {
    if (typeof digitId != 'undefined') gDigitId = digitId;

    changeStyle($('digit_' + gDigitId), 'single_picture');
    gOverDigit = null;

    if (gDigitsCache[gAlbumId].album.numMedia > 0) {
        openDialog('edit_public_media.html', null, 682, backToPublicAlbum, true, 'screen', false, true);
        dhtmlHistory.add("digit;digitId=" + digitId + "&labelId=" + gAlbumId);
    } else {
        openDialogSimple('p_edit_no_media.html');
    }
}

/* callback for open public media dialog */
function backToPublicAlbum() {
    var mediaplayer = $('mediaplayer');
    if (mediaplayer && mediaplayer.DoStop) mediaplayer.DoStop();
    //	removeMediaPlayer('editPicImg', 'mediaplayer');
    dhtmlHistory.add("album;labelId=" + gAlbumId);
}
/* callback for open public media dialog */
function backToPublicAlbumsList() {
    var mediaplayer = $('mediaplayer');
    if (mediaplayer && mediaplayer.DoStop) mediaplayer.DoStop();
    //	removeMediaPlayer('editPicImg', 'mediaplayer');
    renderPublicAlbumsList();
}

/* open share in dialog */
function openShareDialog(templateName, data, width) {
    openDialog(templateName, data, width);
    if (gIsLoggedIn) {
        getUserCountryCode();
        createContactsList(); // force recreation of contacts list
        new Autocompleter.Local('share_address', 'share_address_list', gUserContactsAddressList, {tokens:',', choices : 100, partialChars : 1, afterUpdateElement:addcomma, displayArray:gUserContactsDisplayList, fullSearch:true});
    }
}

/* open add album and move selected media to it */
function openAddAlbumAndMoveTo() {
    instantHideMoveToFolderMenu();
    instantHideDigitMenu();
    if (gArrSelectedDigits.length == 0) {
        gArrSelectedDigits.push(gDigitId);
    }
    openDialog('p_create_album_and_moveto.html', '{shareLevel:"' + gDigitsCache[gAlbumId].album.shareLevel + '"}', 437, cancelMultipleSelection);
}

/* open report block content */
function openReportBlockContent() {
    openDialog('p_report_digit.html', null, 437);
}

/* hide digit controlers */

var insideDigitControlsTimeout = null;

function displayDigitControls() {
    displayElement('digitImageControls');
    if (insideDigitControlsTimeout) clearTimeout(insideDigitControlsTimeout);
}
function hideDigitControls() {
    if (insideDigitControlsTimeout) clearTimeout(insideDigitControlsTimeout);
    insideDigitControlsTimeout = setTimeout(hideDigitControls2, 100);
}
function hideDigitControls2() {
    hideElement('digitImageControls');
}


/* ============================== */
/* === FEATURE SET FUNCTIONS === */
/* ============================ */

/* create a new album into which to upload media */
function createNewAlbumToUpload() {
    closeDialog();
    gFolder2Upload = 'PENDING_NEW';
    openDialog('p_create_album.html', 437);
}

/* set folder 2 upload into */
function setFolder2Upload(clickedThumb, folder2Upload) {
    //	if a thumb is allready clicked, clear its borders
    if (gClickedThumb) {
        gClickedThumb.style.border = 'none';
        gClickedThumb.style.marginBottom = '14px';
    }
    // clearTheVars
    gClickedThumb = null;
    gFolder2Upload = null;

    gFolder2Upload = folder2Upload;
    gClickedThumb = clickedThumb.parentNode;
    if ($('uploadGlobalContinueBtn_dis').style.display != 'none') {
        $('uploadGlobalContinueBtn_dis').style.display = 'none';
        $('uploadGlobalContinueBtn').style.display = 'inline';
    }
    gClickedThumb.style.border = '1px solid #ffffff';
    gClickedThumb.style.marginBottom = '12px';
}

/* open upload dialog from home page 'add media' button */
function openUploadFromHP() {
    closeDialog();
    openDialog('p_upload_new.html', gDigitsCache[gFolder2Upload].album, 460);
    gFolder2Upload = null;
}

/* set share digit */
function setShareDigit() {
    instantHideDigitMenu();
    var digit = getDigitById(gAlbumId, gDigitId);
    setDigitAttachment(digit, gAlbumId, false);
}
/* set share album */
function setShareAlbum(albumId) {
    setAlbumAttachment(false, albumId, false);
}
/* set share zone */
function setShareZone() {
    if ($('avatar_image')) {
        setZoneAttachment($('avatar_image'), null);
    }
}

/* share album / place */
function preShareLink(fAddress, fMsg, albumId, shareArea) {
    var errMsg = "";
    var recipients = createRecipientsFromQuery(fAddress);
    if (recipients.length == 0) {
        errMsg = TEXT.please_enter;
    } else {
        //add validation here
    }
    var msg = $(fMsg).value;
    if (msg == TEXT.type_your_message_here) {
        msg = '';
    }

    if (errMsg != "") {
        openDialog('p_error.html', {error:errMsg}, 414);
    } else {
        //		var username = gUser.username;
        //		if (username == "")
        var username = gPublicUser.username;

        var shareAreaTO = new Object();
        shareAreaTO.userName = username;
        shareAreaTO.albumId = albumId;
        shareAreaTO.digitId = null;
        shareAreaTO.shareArea = shareArea;
        CM.sendRequest('shareLink$AP', recipients, msg, shareAreaTO, TransactionId.next());
    }
}

/* callback for shareLink$AP */
function doShareLink() {
    closeDialog();
    openDialog('p_message_sent.html', null, 230);
}

/* pre send digit */
function preSendDigit(fAddress, fMsg, labelId, digitId) {
    var errMsg = "";
    var recipients = createRecipientsFromQuery(fAddress);

    if (recipients.length == 0) {
        errMsg = TEXT.please_enter;
    } else {
        //add validation here
    }

    if (errMsg != "") {
        openDialog('p_error.html', {error:errMsg}, 414);
    } else {
        var msg = $(fMsg).value;
        if (msg == TEXT.type_your_message_here) {
            msg = '';
        }
        if (digitId) {
            CM.sendRequest('forwardFromBackPack$AP', digitId, recipients, msg, gPublicUser.username, TransactionId.next());
        } else {
            CM.sendRequest('sendDigit$AP', labelId, digitId, recipients, msg, TransactionId.next());
        }
    }
}
function showSentMessageDialog() {
    if (gUserState != 'PUBLIC') {
        setFeedbackMessage('feedbackMessage', TEXT.sending_message, true, 3000);
    } else {
        closeDialog();
        openDialog('p_message_sent.html', null, 230);
    }
}

/* callback for sendDigit$AP */
function doSendMessage() {
    var response = arguments[0];

    switch (response) {
        case "SUCCESS" :
            $('quick_message_to').value = '';

            // Force the notification to load after a message has been sent.
            // This is done in case the credits have reached 0 which should
            // display a proper notification.
            if (!gNotification) {
                gNotification = TM.loadAndParse('notifications.html', null, 'notificationBox');
                notificationsCheck();
            }

            clearComposer();
            showSentMessageDialog();
            break;
        case "INVALID_RECIPIENT_ADDRESS":
            openDialog('p_error.html', {error:TEXT.invalid_recipient_number, showButton:true, buttonText:TEXT.ok, title:TEXT.invalid_recipient_number_title, style:true, focusAt:'quick_message_to'}, 300, null, null, null, null, null, $('messageComposer'), 20, 0);
            break;
        default:
            openDialog('p_message_failed.html', TEXT, 244);
            break;
    }
}

/* edit current album */
function editAlbum() {
    var cbShareLevelPublic = $('share_level_public');
    var cbShareLevelPrivate = $('share_level_private');
    var shareLevel;
    if (cbShareLevelPublic && cbShareLevelPublic.checked)
        shareLevel = 'PUBLIC'
    else
        shareLevel = 'PRIVATE';

    var errMsg = '';
    var albumName = $('album_name');
    if (albumName && $N(albumName.value.strip()) == null) {
        errMsg = TEXT.please_enter_album_name;
    }
    if (albumName && albumName.value.length > 20) {
        errMsg = TEXT.album_name_is_too_long;
    }

    if (shareLevel == 'PUBLIC') {
        for (var digitId in gDigitsCache[gAlbumId].digits) {
            if (gDigitsCache[gAlbumId].digits[digitId].mediaType == 'AUDIO') {
                errMsg = TEXT.the_album_contains_audio;
            }
        }
    }

    if (errMsg != '') {
        openDialog('p_error.html', {error:errMsg}, 414);
        return;
    }

    var objAlbum = new Object();
    objAlbum.id = gAlbumId;
    objAlbum.name = albumName.value;
    objAlbum.description = '';
    objAlbum.shareLevel = shareLevel;
    objAlbum.representativeDigitId = gDigitsCache[gAlbumId].album.representativeDigitId;
    CM.sendRequest('updateLabel$AP', objAlbum.id, objAlbum.name, objAlbum.description, objAlbum.shareLevel, objAlbum.representativeDigitId);
    gDigitsCache[gAlbumId].album.name = albumName.value;
    gDigitsCache[gAlbumId].album.shareLevel = shareLevel;
}

/* callback for updateLabel$AP */
function updateAlbumList(albumsList) {
    closeDialog();
    renderAlbumList();
}

/* reRender the album list according to the current block */
function renderAlbumList(albumsList) {
    if (albumsList) gDigitsCacheManager.addAlbums(albumsList, 'FOLDER', false);
    if (gAlbumId) {
        gNavBlock = TM.loadAndParse('nav_album_pics.html', null, 'navBlock');
    }
}

/* delete album */
function deleteAlbum() {
    gDigitsCacheManager.cleanCache('ALBUM', [gAlbumId]);
    CM.sendRequest('removeLabel$AP', gAlbumId);
    gAlbumId = null;
}

/* callback for removeLabel$AP */
function updateAlbumListAfterRemoveAlbum() {
    closeDialog();
    renderAlbumsListPage();
}

/* create new album */
var gNewAlbumBeenCreatedNow = false;

function addAlbum(moveTo) {
    if (!gNewAlbumBeenCreatedNow) {
        var errMsg = '';
        var albumName = $('album_name');

        if (albumName && albumName.value.strip() == "") {
            errMsg = TEXT.please_enter_album_name;
        }
        if (albumName && albumName.value.length > 20) {
            errMsg = TEXT.album_name_is_too_long;
        }
        if (errMsg != "") {
            openDialog('p_error.html', {error:errMsg}, 414);
            return;
        }

        // Bug #2203, only change the gNewAlbumBeenCreatedNow to true if
        // all validations has been successfuly completed
        gNewAlbumBeenCreatedNow = true;
        var cbShareLevelPublic = $('share_level_public');
        var cbShareLevelPrivate = $('share_level_private');
        var shareLevel;
        if (cbShareLevelPublic && cbShareLevelPublic.checked)
            shareLevel = 'PUBLIC'
        else
            shareLevel = 'PRIVATE';

        var objAlbum = new Object();
        objAlbum.name = albumName.value;
        objAlbum.description = '';
        objAlbum.shareLevel = shareLevel;

        if (moveTo) {
            if (checkMoveToNewFolder(shareLevel, gAlbumId, gDigitId)) CM.sendRequest('createNewLabel$updateAlbumList_and_moveTo', objAlbum.name, objAlbum.description, objAlbum.shareLevel);
        } else {
            CM.sendRequest('createNewLabel$updateAlbumListAfterAdd', objAlbum.name, objAlbum.description, objAlbum.shareLevel);
        }
    }
}


/* callback for createNewLabel$updateAlbumListAfterAdd */
function updateAlbumListAfterAdd(album) {
    closeDialog();
    album.numMedia = 0;	// fix because server doesn't send this
    var albumsList = { albumTOList : [album] };
    gDigitsCacheManager.addAlbums(albumsList, 'FOLDER', false);
    renderAlbumsListPage();
    // if created new album from the 'add media' button in the home page
    if (gFolder2Upload == 'PENDING_NEW') {
        gFolder2Upload = album.id;
        openUploadFromHP();
    }
    //CM.sendRequest('getUserAlbums$renderAlbumsListPage',createAlbumsQuery());
    gNewAlbumBeenCreatedNow = false;
}

/* callback for createNewLabel$updateAlbumList_and_moveTo */
function updateAlbumList_and_moveTo(album) {
    // gArrSelectedDigits get emptied in the close callback of the create folder dialog - so keeping in in temp variable
    var arrSelectedDigits = gArrSelectedDigits;
    closeAllDialogs();
    gArrSelectedDigits = arrSelectedDigits;

    album.numMedia = 0;	// fix because server doesn't send this
    var albumsList = { albumTOList : [album] };
    gDigitsCacheManager.addAlbums(albumsList, 'FOLDER', false);
    moveToFolder(album.id); // send first album since it is the newly created album
    gNewAlbumBeenCreatedNow = false;
}

/* open upload avatar dialog */
function uploadAvatar() {
    if (gDragging) return;
    openDialog('p_upload_avatar.html', null, 400);
}

/* delete media */
function deleteDigit() {
    closeDialog();
    var digit = getDigitById(gAlbumId, gDigitId);
    gDigitsCacheManager.deleteDigits(gAlbumId, [digit.digitId]);
    CM.sendRequest('updateCabinetDigitHeaders$AP', createDigitsOperationQuery([digit], 'DELETE_OBJECT'));
}

/* delete multiple digits */
function deleteMultipleDigits() {
    closeDialog();
    hideElement('moveToFolder_Panel');
    gDigitsCacheManager.deleteDigits(gAlbumId, gArrSelectedDigits);
    CM.sendRequest('deleteDigitsFromAlbum$AP', gArrSelectedDigits, gAlbumId, TransactionId.next());
    gArrSelectedDigits = [];
}

/* callback for updateCabinetDigitHeaders$AP */
function doUpdateCabinetDigitHeaders() {
    closeAllDialogs();
    var method = (gAlbumId == gSystemLabels.PLAYLIST) ? 'cacheDigits$showMusicAlbum' : 'cacheDigits$renderAlbumPage';
    gDigitsCacheManager.getDigits(gAlbumId, 1, gDigitsCache[gAlbumId].album.numMedia, method);
}

/* cancel multiple digit selection and close toaster */
/* Bug 3259 fix, check if open album is playlist or not */
function cancelMultipleSelection() {
    for (var i = 0; i < gArrSelectedDigits.length; i++) {
        if (gAlbumId == gSystemLabels.PLAYLIST) {
            var chkbx = $('ckbx_' + gArrSelectedDigits[i]);
            changeCkbxParentClassname(chkbx);
            chkbx.checked = (!chkbx.checked); // Toggle checkbox selection

        } else {
            changeStyle($('digit_' + gArrSelectedDigits[i]), 'single_picture');
        }
    }
    gArrSelectedDigits = [];
    hideElement('moveToFolder_Panel');
}

/* pre send to mobile */
function preSendToMobile() {
    instantHideDigitMenu();
    var digitId = getDigitById(gAlbumId, gDigitId).digitId;
    CM.sendRequest('forwardDigit$doSendToMyPhone', gAlbumId, digitId, [new RecipientTO(gUser.userId, null, 'SENDER_USER')], '', TransactionId.next());
}
/* callback for sendDigit$doSendToMobile */
function doSendToMobile() {
    openDialog('p_digit_sent.html', null);
}

/* pre set album cover */
function preSetAlbumCover() {
    instantHideDigitMenu();
    var objAlbum = new Object();
    objAlbum.id = gAlbumId;
    objAlbum.name = gDigitsCache[gAlbumId].album.name;
    objAlbum.description = '';
    objAlbum.shareLevel = gDigitsCache[gAlbumId].album.shareLevel;
    objAlbum.representativeDigitId = gDigitsCache[gAlbumId].album.representativeDigitId = getDigitById(gAlbumId, gDigitId).digitId;
    CM.sendRequest('updateLabel$setAlbumCover', objAlbum.id, objAlbum.name, objAlbum.description, objAlbum.shareLevel, objAlbum.representativeDigitId);
}
/* callback for updateLabel$setAlbumCover */
function updateAlbumsListAndSetAlbumCover() {
    CM.sendRequest('getUserAlbums$setAlbumCover', createAlbumsQuery());
}
/* callback for getUserAlbums$setAlbumCover */
function doSetAlbumCover(albumsList) {
    findMusicPlaylistAlbum(albumsList);
    if (albumsList) gDigitsCacheManager.addAlbums(albumsList, 'FOLDER', false);
    var album = gDigitsCache[gAlbumId].album;
    var albumMediaCover = $("mediaAlbumCover");
    if (albumMediaCover) albumMediaCover.src = gAlbumspath + "getImage?mediaLocation=" + album.albumRepresentativeDigitLocation + "&sizeTemplate=AlbumThumbnail&mediaRadiusAngle=" + album.albumRepresentativeDigitRotationDegrees;
    openDialog('p_album_cover_set.html', null);
}

/* save digit local */
function downloadFile() {
    var digit;
    if (typeof gOpenMessage != 'undefined' && gOpenMessage.digitId) {
        digit = getDigitById(gOpenMessage.albumId, gOpenMessage.digitId);
    } else {
        digit = getDigitById(gAlbumId, gDigitId);
    }
    var url = gAlbumspath + 'getImage?mediaLocation=' + digit.storageLocation + '&sizeTemplate=DigitOriginalSize&digitId=' + digit.digitId + '&mediaRadiusAngle=' + digit.rotationDegrees + '&caption=' + encodeURI(digit.digitCaption) + '&download=true';
    window.open(url);
}

/* open full screen digit */
function openFullScreenDigit() {
    var digit = getDigitById(gAlbumId, gDigitId);
    var url = gAlbumspath + "getImage?mediaLocation=" + digit.storageLocation + "&sizeTemplate=DigitOriginalSize&digitId=" + digit.digitId + '&mediaRadiusAngle=' + digit.rotationDegrees;
    window.open(url, "_blank");
}

/* move to folder */
function moveToFolder(targetAlbumId) {
    // hide MoveToFolder or Digit menu, whichever one is open
    instantHideMoveToFolderMenu();
    instantHideDigitMenu();

    var srcAlbumId;
    var messgaeDialog = $('messgaeDialog');
    if (messgaeDialog) {
        srcAlbumId = gOpenMessage.albumId;
        var digitId = gOpenMessage.digitId;
        var digit = getDigitById(srcAlbumId, digitId);
        var arrDigitsToUpdate = checkMoveToFolder(targetAlbumId, srcAlbumId, digitId);
        if (!arrDigitsToUpdate) return;
        // duplicate the digit and move the duplicate into target album
        var clonedDigitList = gDigitsCacheManager.cloneDigitsAsList(srcAlbumId, [digitId]);
        gDigitsCacheManager.addDigits(targetAlbumId, clonedDigitList);
        CM.sendRequest('copyDigitsFromInboxToBackpack$AP', [digitId], targetAlbumId, TransactionId.next());
    } else {
        srcAlbumId = gAlbumId;
        var arrDigitsToUpdate = checkMoveToFolder(targetAlbumId, gAlbumId, gDigitId);
        if (!arrDigitsToUpdate) return;
        var arrDigitIDs = [];
        for (var i = 0; i < arrDigitsToUpdate.length; i++) {
            arrDigitIDs.push(arrDigitsToUpdate[i].digitId);
        }
        var dialog = null;
        if (Dialog.prototype.currentInstance) dialog = Dialog.prototype.openedDialogs[Dialog.prototype.currentInstance];
        var totalDigitCount = $('totalDigitCount')
        if (dialog && dialog.showing && totalDigitCount) { // if moving to folder from single media view
            var numMedia = gDigitsCache[gAlbumId].album.numMedia;
            if (numMedia - 1 > 0) {
                totalDigitCount.innerHTML = numMedia - 1;
            }
            // if got more than 1 digit in album, show next digit, else close dialog
            if (getSortedDigitsList(targetAlbumId).length > 1) {
                editPicPaging(1);
            } else {
                closeDialog();
            }
        }
        gDigitsCacheManager.moveDigits(arrDigitIDs, gAlbumId, targetAlbumId);
        gArrSelectedDigits = [];
        hideElement('moveToFolder_Panel');
        gFolderFeedbackMessage = ['folderFeedbackMessage', TEXT.media_moved.parse(targetAlbumId, gDigitsCache[targetAlbumId].album.name), false, 3000];
        if (gAlbumId == gSystemLabels.RECENTLY_RECEIVED) {
            CM.sendRequest('copyDigitsFromInboxToBackpack$AP', arrDigitIDs, targetAlbumId, TransactionId.next());
        } else {
            CM.sendRequest('moveDigits$AP', arrDigitIDs, srcAlbumId, targetAlbumId, TransactionId.next());
        }
    }
}

/* check if ok to perform move to folder, and prepare array of digits to move */
function checkMoveToFolder(targetAlbumId, srcAlbumId, digitId) {
    var arrDigitsToUpdate = [];
    gArrSelectedDigits = gArrSelectedDigits.compact();
    if (gArrSelectedDigits.length == 0) {
        gArrSelectedDigits.push(digitId);
    }
    for (var i = 0; i < gArrSelectedDigits.length; i++) {
        arrDigitsToUpdate.push(getDigitById(srcAlbumId, gArrSelectedDigits[i]));
        if (arrDigitsToUpdate[i].mediaType == "AUDIO" && gDigitsCache[targetAlbumId].album.shareLevel != "PRIVATE") {
            openDialog('p_moveto_album_no_audio.html', null);
            return false;
        } else if (targetAlbumId == gSystemLabels.PLAYLIST && arrDigitsToUpdate[i].mediaType != "AUDIO") {
            openDialog('p_moveto_album_only_audio.html', null);
            return false;
        }
    }
    if (arrDigitsToUpdate.length == 0) {
        openDialog('p_moveto_album_no.html', null);
        return false;
    }
    return arrDigitsToUpdate;
}

/* check if ok to perform move to folder, and prepare array of digits to move */
function checkMoveToNewFolder(targetAlbumShareLevel, srcAlbumId, digitId) {
    var arrDigitsToUpdate = [];
    gArrSelectedDigits.compact();
    if (gArrSelectedDigits.length == 0) {
        gArrSelectedDigits.push(digitId);
    }
    for (var i = 0; i < gArrSelectedDigits.length; i++) {
        arrDigitsToUpdate.push(getDigitById(srcAlbumId, gArrSelectedDigits[i]));
        if (arrDigitsToUpdate[i].mediaType == "AUDIO" && targetAlbumShareLevel != "PRIVATE") {
            openDialog('p_moveto_album_no_audio.html', null);
            return false;
        }
    }
    if (arrDigitsToUpdate.length == 0) {
        openDialog('p_moveto_album_no.html', null);
        return false;
    }
    return arrDigitsToUpdate;
}

/* pre report block content */
function preReportBlockContent(reasonFld, emailId) {
    var from = encodeURI($(emailId).value);
    var reason = $(reasonFld).value.stripScripts().stripTags() + "\n\n" + TEXT.from + ': ' + from;
    var url = getPublicPageUrl(gPublicUser.username, gAlbumId) + "/" + gDigitId;
    CM.sendRequest('reportBlockContent$AP', url, reason);
}

/* callback for reportBlockContent$AP */
function doReportBlockContent() {
    closeDialog();
}

/* called at the response of upload.form */
function showUploadProgress() {
}


function changeDetails() {
    var firstName = $F('changeDetailsFirstName');
    var lastName = $F('changeDetailsLastName');
    var errMsg = '';
    var alphaNumExp = /^[0-9a-zA-Z ]+$/;

    if (firstName.match(alphaNumExp) == null)
        errMsg += '<p>' + TEXT.input_first_name + '<br/></p>';
    if (lastName.match(alphaNumExp) == null)
        errMsg += '<p>' + TEXT.input_last_name + '<br/></p>';

    if (errMsg) {
        openDialog('p_error.html', {error:errMsg, showButton:true, buttonText:TEXT.close}, 313);
        return false;
    } else {
        gNickname = firstName + ' ' + lastName;
        CM.sendRequest('updateDetails$AP', firstName, lastName, gUser.userTO.primaryCommunicationAddress.communicationAddress);
        return true;
    }
}
function doUpdateDetails(status) {
    if (status == 'OK') {
        var errMsg = "Your details were successfully updated."
        openDialog('p_error.html', {error:errMsg, showButton:true, buttonText:TEXT.close}, 313);
        $I('nicknameDiv', gNickname);
        setTimeout(function() {
            closeAllDialogs();
        }, 2000);

        return true;
    }
    return false;
}

/* leave the service */
function leaveTheService() {
    var username = $F('leaveServiceUsername');
    var password = $F('leaveServicePassword');
    var mobile = $F('leaveServiceMobile');
    var fullMobile = validateNumber(mobile);
    var agree = $F('leaveServiceAgree');
    var errMsg = '';
    if (!username || !password || !mobile || !agree) {
        if (!username) errMsg += '<p>' + TEXT.input_user + '<br/><br/></p>';
        if (!password) errMsg += '<p>' + TEXT.input_password + '<br/><br/></p>';
        if (!mobile) errMsg += '<p>' + TEXT.input_mobile + '<br/><br/></p>';
        if (errMsg == '' && !agree) errMsg += '<p>' + TEXT.input_agree + '</p>';
    } else if (username != gUser.username) {
        errMsg = TEXT.invalid_user_name;
    } else if (fullMobile != gUser.userTO.primaryCommunicationAddress.communicationAddress) {
        errMsg = TEXT.input_mobile_no_match;
    }

    if (errMsg != '') {
        openDialog('p_error.html', {error:errMsg, showButton:true, buttonText:TEXT.close}, 313);
    } else {
        CM.sendRequest('leaveTheService$AP', username, password, fullMobile);
    }
}
/* callback for leaveTheService$AP */
function doLeaveTheService(status) {
    if (status == 'OK') {
        openDialog('p_error.html', {error:TEXT.you_successfully_left_the_service, showButton:true, buttonText:TEXT.close}, 313);
        closeAllDialogs();
        beforeLogout();
        return;
    }
    var errMsg = '';
    if (status == 'INCORRECT_PASSWORD') {
        errMsg = TEXT.incorrect_password + '<br /><br />' + TEXT.please_try_again_later;
    } else if (status == 'OPERATION_FAILED') {
        errMsg = TEXT.there_was_a_problem_leaving_the_service + '<br /><br />' + TEXT.please_try_again_later;
    }

    if (errMsg != '') {
        openDialog('p_error.html', {error:errMsg, showButton:true, buttonText:TEXT.close}, 313);
    }
}

/* loader */
var gLoader = {
    count : 0,
    createLoader : function() {
        var loader = document.createElement('p');
        loader.id = 'loaderMessage';
        loader.className = 'loaderMessage alertCompo txt';
        loader.style.display = 'none';
        loader.style.zIndex = '2000';
        loader.innerHTML = '<span>' + TEXT.loading + '</span>';
        document.body.appendChild(loader);
    },
    showLoader : function(rlabel) {
        if (rlabel == 'getClientResponse$AP') return;
        if (this.count == 0) {
            $('loaderMessage').style.top = document.documentElement.scrollTop + 'px' || '0px';
            displayElement('loaderMessage');
        }
        this.count++;
    },
    hideLoader : function(rlabel) {
        if (rlabel == 'getClientResponse$AP') return;
        this.count--;
        if (this.count < 0) this.count = 0;
        if (this.count == 0) hideElement('loaderMessage');
    }
}

/* public logged-in keep alive */
function keepAlive() {
    CM.sendRequest('getClientPublicResponse$AP');
}
/* callback for getClientPublicResponse$AP */
function doKeepAlive(notification) {
    var timeout = notification.timeout || 40000;
    setTimeout(keepAlive, timeout);
}

/* ================================ */
/* === DIGIT & PAGE NAVIGATION === */
/* ============================== */
/* digit paging */
function editPicPaging(distance) {
    gDigitId = (isNaN(distance)) ? distance : getAdjacentDigitIdById(gAlbumId, gDigitId, distance);
    dhtmlHistory.add("digit;digitId=" + gDigitId + "&labelId=" + gAlbumId);
    removeMediaPlayer();
    if (gUserState == 'PUBLIC') {
        TM.loadAndParse('edit_public_media.html', null, 'dialog1Content');
    } else {
        TM.loadAndParse('edit_media.html', null, 'dialog1Content');
    }
    addEditMoveToFolderListeners();
}

/* sets single image when loaded */
function setSingleImage() {
    var digitImage = $('digitImage');
    if (digitImage) digitImage.src = gSingleImg.src;
}

function showDigitMenu() {
}

/* === HISTORY === */
/* handle history change */
function handleHistoryChange(newLocation) {
    if (!gHistoryFlag) return;
    var hd = getHistoryData(newLocation);
    var params = hd.params;

    switch (hd.context) {
        case "albums":
            if (gUserState == "PUBLIC") {
                renderPublicAlbumsList();
            } else {
                renderAlbumsListPage();
            }
            closeAllDialogs();
            break;
        case "album":
            var albumId = $N(params["labelId"]);
            if (gUserState == "PUBLIC") {
                initPublicAlbumPage(albumId);
            } else {
                initAlbumPage(albumId);
            }
            closeAllDialogs();
            break;
        case "digit":
            if (gUserState == "PUBLIC") {
                //				initPublicAlbumPage();
            } else {
                try {
                    var dialog = null;
                    if (Dialog.prototype.currentInstance) dialog = Dialog.prototype.openedDialogs[Dialog.prototype.currentInstance];
                    var digitId = $N(params['digitId']);
                    if (dialog && dialog.showing) {
                        editPicPaging(digitId);
                    } else {
                        openDialog('edit_media.html', null, 682, backToAlbum, true, 'screen', false, true);
                        dhtmlHistory.add("digit;digitId=" + digitId + "&labelId=" + gAlbumId);
                    }
                } catch(e) {
                }
            }
            break;
    }
}
function flip_digit_reading_states() {

    var digitTextCont = $('digitTextCont').style;
    var digitMediaCont = $('digitMediaCont').style;
    var button = $('butt_save_to_folder').style;
    if (digitTextCont.display == '' || digitTextCont.display == 'block') {
        digitTextCont.display = 'none';
        digitMediaCont.display = 'block';
        button.display = 'block';
    } else {
        digitTextCont.display = 'block';
        digitMediaCont.display = 'none'
        button.display = 'none';
    }

    // local vars
    var lDigitText = $('digitText');  //left
    var lDigitMedia = $('digitMedia');  //right
    var mvCpArrwLeft = $('mvCpArrwLeft');
    var mvCpArrwRight = $('mvCpArrwRight');

    //switch buttons states
    if (lDigitText.className == 'mvCpBtn cursorPointer') {
        lDigitText.className = 'mvCpBtnChosen cursorDefault';
        lDigitText.href = 'javascript:void(0)';
    } else {
        lDigitText.className = 'mvCpBtn cursorPointer';
        lDigitText.href = 'javascript:void(flip_digit_reading_states())';
    }
    if (lDigitMedia.className == 'mvCpBtn cursorPointer') {
        lDigitMedia.className = 'mvCpBtnChosen cursorDefault';
        lDigitMedia.href = 'javascript:void(0)';
    } else {
        lDigitMedia.className = 'mvCpBtn cursorPointer';
        lDigitMedia.href = 'javascript:void(flip_digit_reading_states())';
    }

    //switch arrows states
    if (mvCpArrwLeft.className == 'mvCpArrwLeftOn cursorPointer') {
        mvCpArrwLeft.className = 'mvCpArrwLeftOff cursorDefault';
        mvCpArrwLeft.href = 'javascript:void(0)';
    } else {
        mvCpArrwLeft.className = 'mvCpArrwLeftOn cursorPointer';
        mvCpArrwLeft.href = 'javascript:void(flip_digit_reading_states())';
    }
    if (mvCpArrwRight.className == 'mvCpArrwRightOn cursorPointer') {
        mvCpArrwRight.className = 'mvCpArrwRightOff cursorDefault';
        mvCpArrwRight.href = 'javascript:void(0)';
    } else {
        mvCpArrwRight.className = 'mvCpArrwRightOn cursorPointer';
        mvCpArrwRight.href = 'javascript:void(flip_digit_reading_states())';
    }
}

// change Phone PresenceState FROM Button

var gPresenceStateClassEnum = {
    Always : 'SEND',
    Online : 'DONT_SEND_WHILE_ONLINE',
    Never : 'DONT_SEND'
}
var gTmpPresenceState;
var gIsSettingsChanged = false;

/* change presence from radio buttons */
function changePhoneState(state) {
    if (!state || state == gDataCookie.presence) return;
    gTmpPresenceState = state;
    CM.sendRequest('setPresenceState$AP', gPresenceStateClassEnum[state], TransactionId.next());
    //writeUIModeToCookie();
}
/* callback for setPresenceState$AP */
function callbackPhoneState(callBackAnswer) {
    if (callBackAnswer) {
        if (!gMobileAlerts) {
            displayElement($('mobileAlerts'));
            gMobileAlerts = TM.loadAndParse('mobileAlerts.html', null, 'mobileAlerts');
        }
        switch (gTmpPresenceState) {
            case 'Always':
                gDataCookie.presence = gTmpPresenceState;
                gDataCookie.settingsPresence = gTmpPresenceState;
                break;
            default:
                gDataCookie.presence = gTmpPresenceState;
                break;
        }
        if (gDataCookie.presence == 'Always') {
            $('always_send').checked = true;
        } else {
            $('dont_send_while_online').checked = true;
        }
        writeUIModeToCookie();
    } else {
        openDialog('p_error.html', {error:TEXT.please_try_again}, 414);
    }
    gTmpPresenceState = null;
}

/* set mobile alerts radio buttons on/off */
function setMobileAlertsState(state) {
    if (state) {
        $('always_send').checked = true;
        $('dont_send_while_online').checked = false;
    } else {
        $('always_send').checked = false;
        $('dont_send_while_online').checked = true;
    }
}

/* change presence in settings dialog */
function changePhoneStateFromSettings(ckBx) {
    gTmpPresenceState = ($(ckBx).checked) ? 'Always' : 'Never';
    CM.sendRequest('setPresenceStateFromSettings$AP', gPresenceStateClassEnum[gTmpPresenceState], TransactionId.next());
}

/* callback for setPresenceStateFromSettings$AP */
var gMobileAlertsTimeout = null;
function callbackFromSettingsPhoneState(callBackAnswer) {
    if (gMobileAlertsTimeout) clearTimeout(gMobileAlertsTimeout);
    if (callBackAnswer) {
        switch (gTmpPresenceState) {
            case 'Always':
                gDataCookie.settingsPresence = gTmpPresenceState;
                break;
            case 'Never':
                gDataCookie.presence = gTmpPresenceState;
                gDataCookie.settingsPresence = gTmpPresenceState;
                setMobileAlertsState(false);
                break;
        }
        writeUIModeToCookie();
        $('mobileAlertsStats').innerHTML = TEXT.mobile_alerts_status_changed;
        $('mobileAlertsStats').className = 'settings_secondSpan mobileAlertsStats clearfix colorGreen';
    } else {
        $('mobileAlertsStats').innerHTML = TEXT.mobile_alerts_status_changed;
        $('mobileAlertsStats').className = 'settings_secondSpan mobileAlertsStats clearfix colorOrange';
    }
    gTmpPresenceState = null;
    gIsSettingsChanged = false;
    gMobileAlertsTimeout = setTimeout('$(\'mobileAlertsStats\').innerHTML = \'\'', 1500);
}

function openPhoneSettingsDialog() {
    openDialog('settings.html', null, 575, null, true, 'clear', false, false);
}

/** ============================ */
/** === Pre Loading Images === */
/** ========================== */

function ImagePreloader() {
    var arr = $A(arguments);
    var img;
    for (var i = 0, leni = arr.length; i < leni; i++) {
        img = new Image();
        img.src = '/WebGW/pages/triplay/images/' + arr[i];
        img.onerror = function() {
            if (console && console.error) console.error('Image not found using ImagePreloader: ' + img.src);
        }
    }
}

function preloadAllImages() {
    ImagePreloader('bg/orangePictureHolder.gif', 'bg/whats_thisTop.png',
            'bg/whats_thisTop.gif', 'bg/whats_thisBody.gif', 'bg/whats_thisBottom.gif', 'btns/x_box_button.gif', 'btns/x_box_buttonDown.gif',
            'btns/x_box_buttonOn.gif', 'bg/orange_folder.jpg', 'icons/shareFolderByEmailOn.gif', 'icons/shareFolderByEmailDown.gif', 'bg/folderMenuLOn.gif',
            "bg/folderMenuLDown.gif", "bg/folderMenuMOn.gif", "bg/folderMenuMDown.gif", "bg/folderMenuMDis.gif",
            "bg/folderMenuROn.gif", "bg/folderMenuRDown.gif", "bg/folderMenuMOnPrvt.gif", "bg/folderMenuMDownPrvt.gif",
            "btns/genericBtns/verySmallLeftOn.gif", "btns/genericBtns/verySmallBodyOn.gif", "btns/genericBtns/verySmallRightOn.gif",
            "btns/genericBtns/verySmallRightDown.gif", "btns/genericBtns/verySmallBodyDown.gif", "btns/genericBtns/verySmallLeftDown.gif",
            "btns/genericBtns/smallLeftOn.gif", "btns/genericBtns/smallBodyOn.gif", "btns/genericBtns/smallRightOn.gif",
            "btns/genericBtns/smallLeftDown.gif", "btns/genericBtns/smallBodyDown.gif",
            "btns/genericBtns/smallRightDown.gif", "btns/genericBtns/normalBtnLeftOn.gif", "btns/genericBtns/normalBtnBodyOn.gif",
            "btns/genericBtns/normalBtnRightOn.gif", "btns/genericBtns/normalBtnLeftDown.gif", "btns/genericBtns/normalBtnBodyDown.gif",
            "btns/genericBtns/normalBtnRightDown.gif", "btns/genericBtns/selectBtnBody_on.gif",
            "btns/genericBtns/selectBtnBody_down.gif", "btns/genericBtns/selectBtnLeft_down.gif",
            "btns/genericBtns/selectBtnLeft_on.gif", "btns/genericBtns/smallFatBtnDwn.gif",
            "btns/genericBtns/smallFatBtnOn.gif", "btns/genericBtns/fatBtnDwn.gif",
            "btns/genericBtns/fatBtnOn.gif", "dialogs/smallBtnDown.gif", "dialogs/smallBtnOn.gif",
            "btns/genericBtns/shrinkedBtnDwn.gif", "btns/genericBtns/shrinkedBtnOn.gif",
            'dialogs/pop_top.gif', 'dialogs/pop_top_left.gif', 'dialogs/pop_top_right.gif',
            'dialogs/pop_bottom_right.gif', 'dialogs/pop_bottom_left.gif', 'dialogs/pop_bottom.gif', 'btns/genericBtns/smallRightOn.gif',
            'btns/genericBtns/smallBodyOn.gif', 'btns/genericBtns/smallLeftOn.gif', 'btns/genericBtns/smallRight.gif', 'btns/genericBtns/smallBody.gif',
            'btns/genericBtns/smallRightDown.gif', 'btns/genericBtns/smallBodyDown.gif', 'btns/genericBtns/smallLeftDown.gif',
            'lang/de/bg/phoneStatesDialog.gif', 'lang/en/bg/phoneStatesDialog.gif', 'dialogs/pop_top.gif', 'dialogs/pop_top_left.gif',
            'dialogs/pop_top_right.gif', 'dialogs/pop_bottom.gif', 'dialogs/pop_bottom_left.gif', 'dialogs/pop_bottom_right.gif',
            'btns/genericBtns/normalBtnLeft.gif', 'btns/genericBtns/normalBtnBody.gif', 'btns/genericBtns/normalBtnRight.gif');
}
/*
gCookieManager v0.2
setCookie(), getCookie(), deleteCookie()

Author: Orr Siloni

PLEASE NOTE!

This file exists under TPS\modules\WebWG\war\pages\common\js branch and under PublicSite\trunck\js

*/

var gCookieManager = {
	version : '0.2',
	timeEnum : {
		hour : 3600000,
		day : 86400000,
		week : 604800000,
		month : 2592000000,
		year : 31104000000
	},
	isCookieEnabled : function(){
		if(document.cookie) return true;
		document.cookie = 'testCookie=yes';
		return (document.cookie.indexOf('testCookie=yes') != -1);
	}(),	// run the function immediatelly as it is defined
	setCookie : function(name, value, time, path, domain, secure){
		if (!this.isCookieEnabled) return;
		if(time){
			time = (typeof time == 'string' && this.timeEnum[time])? this.timeEnum[time] : (parseInt(time) != isNaN) ? time : 0;
			time = (new Date((new Date()).getTime() + time)).toGMTString();
		}
		document.cookie = [name, '=', escape(value), time?';expires='+time:'', ';path=' , path?path:'/', domain?';domain='+domain : location.hostname.match(/\.\w+\./) != null ? ';domain='+location.hostname : '', secure?';secure':''].join('');
	},
	getCookie : function(name){
		if (!this.isCookieEnabled || !document.cookie) return null;
		var cookies = document.cookie.split(/;\s*/);
		var cookie = null;
		for (var i=0; i < cookies.length; i++){
			if (cookies[i].indexOf(name+'=')==0){
				cookie = cookies[i].substring(name.length+1);
				break;
			}
		}
		return (cookie) ? unescape(cookie) : null;
	},
	deleteCookie : function(name){
		var value = this.getCookie(name);
		this.setCookie(name, value, -1000);
	}
}

function getURLParam(strParamName, doNotUseLower){
	var strReturn = '';
	var strHref = window.location.href;
	if (strHref.indexOf('?') > -1){
        var strQueryString = strHref.substr(strHref.indexOf('?'));
        if (doNotUseLower == undefined) {
            strQueryString = strQueryString.toLowerCase();            
        }

        var aQueryString = strQueryString.split('&');
		for (var i = 0, j = aQueryString.length; i < j; i++ ){
			if (aQueryString[i].indexOf(strParamName.toLowerCase() + '=') > -1 ){
				var aParam = aQueryString[i].split('=');
				strReturn = aParam[1];
				break;
			}
		}
	}
	return unescape(strReturn);
}

/* global cookie data storage */
var gDataCookie = {
	isLoadedFromCookie : false,	// flag if data is default or loaded from cookie
	messagesPerPage : 25,
	lang : gLang,
	presence : 'Always', // Bug #3988 fix, the defualt cookie status is 'Always'
	settingsPresence : 'Always'
}

/* global cookie data storage */
var gDataCookieWithCountry = {
	isLoadedFromCookie : false,	// flag if data is default or loaded from cookie
	lang : gLang,
	country : getURLParam('country').toLowerCase() // Ensure that country parameter doesn't change the basic cookie structure
}

/* gloabl cookie data storage, T-Connect Firefox Extention */
var gDataCookieFF = {
    isLoadedFromCookie : false,	// flag if data is default or loaded from cookie
    lang : gLang,
    username: null,
    password: null,
    rememberMe: false
}

/* gloabl cookie data storage, T-Connect Firefox Extention */
var gDataCookieTempCache = {
    isLoadedFromCookie : false,	// flag if data is default or loaded from cookie
    action: null,
    selectedText: null,
    ver: null,
    img: null
}

/* update UI mode from cookie */
function getUIModeFromCookie(param){
	if (!gDataCookie.isLoadedFromCookie){
		var str = gCookieManager.getCookie('TriplayUserUIMode');
		if (str) gDataCookie = str.evalJSON();
		gDataCookie.isLoadedFromCookie = true;
	}
	return (param && typeof gDataCookie[param] != 'undefined') ? gDataCookie[param] : null;
}

/* update L18N mode from cookie */
function getL18NModeFromCookie(param){
	if (!gDataCookieWithCountry.isLoadedFromCookie){
		var str = gCookieManager.getCookie('TriplayUserL18NMode');
		if (str) gDataCookieWithCountry = str.evalJSON();
		gDataCookieWithCountry.isLoadedFromCookie = true;
	}
	return (param && typeof gDataCookieWithCountry[param] != 'undefined') ? gDataCookieWithCountry[param] : null;
}

/* update FF mode from cookie */
function getFFModeFromCookie(param){
	if (!gDataCookieFF.isLoadedFromCookie){
		var str = gCookieManager.getCookie('TriplayUserFFMode');
		if (str) gDataCookieFF = str.evalJSON();
		gDataCookieFF.isLoadedFromCookie = true;
	}
	return (param && typeof gDataCookieFF[param] != 'undefined') ? gDataCookieFF[param] : null;
}

/* update FF mode from cookie */
function getFromTempChachCookie(param){
	if (!gDataCookieTempCache.isLoadedFromCookie){
		var str = gCookieManager.getCookie('tempCache');
		if (str) gDataCookieTempCache = str.evalJSON();
		gDataCookieTempCache.isLoadedFromCookie = true;
	}
	return (param && typeof gDataCookieTempCache[param] != 'undefined') ? gDataCookieTempCache[param] : null;
}

/* write UI mode to cookie */
function writeUIModeToCookie(){
	gCookieManager.setCookie('TriplayUserUIMode', Object.toJSON(gDataCookie), 'year');
}

/* write UI mode to cookie */
function writeL18NModeToCookie(){
	gCookieManager.setCookie('TriplayUserL18NMode', Object.toJSON(gDataCookieWithCountry), 'year');
}

/* write FF mode to cookie */
function writeFFModeToCookie(){
	gCookieManager.setCookie('TriplayUserFFMode', Object.toJSON(gDataCookieFF), 'year');
}

/* write FF mode to cookie */
function writeTempCahceToCookie(){
	gCookieManager.setCookie('tempCache', Object.toJSON(gDataCookieTempCache), 'year');
}

/* read presence from cookie */
function setPresenceFromCookie(){
	getUIModeFromCookie();
	var tmpPresenceState = gDataCookie.presence;
	gDataCookie.presence = '';
	changePhoneState(tmpPresenceState);
}

/** ====================== */
/** === DIGIT CACHING === */
/** Author: Orr Siloni   */
/** =================== */
/* digits & albums cache object */
var gDigitsCache = { numAlbums : 0, sortedAlbums: {} };

/* new album object */
function albumCacheObject(album){
	if (!album) album = {};
	this.album = album;
	this.digits = {};	// digit objects
	this.cache = {};
	this.cache.sortedDigits = {};	// associative array of digits in different sorts
}

/* digits cache manager */
var gDigitsCacheManager = function(){}
gDigitsCacheManager.sortBy = 'RECEIVED_TIME';
gDigitsCacheManager.sortDir = 'DESC';
gDigitsCacheManager.albumSortBy = 'CREATION_TIME';
gDigitsCacheManager.albumSortDir = 'DESC';

/* Public: add albums to cache */
gDigitsCacheManager.addAlbums = function(albumsList, albumType, reset){
	if (!albumsList) return false;
	if (reset) this.cleanCache("ALL");
	var addedNewAlbums = false;
	var albumId;
	for (var i=0, len = albumsList.albumTOList.length; i < len; i++){
		albumId = albumsList.albumTOList[i].id;
		if (gDigitsCache[albumId]){
			gDigitsCache[albumId].album = albumsList.albumTOList[i];
		} else {
			gDigitsCache[albumId] = new albumCacheObject(albumsList.albumTOList[i]);
			if (!gDigitsCache.sortedAlbums[albumType]) gDigitsCache.sortedAlbums[albumType] = [];
			gDigitsCache.sortedAlbums[albumType].push(albumId);
			addedNewAlbums = true;
			gDigitsCache.numAlbums++;
		}
	}
	if (addedNewAlbums){
		gDigitsCache.sortedAlbums[albumType] = gDigitsCache.sortedAlbums[albumType].sort(gDigitsCacheManager.cmpAlbums);
	}
	return true;
}

/* Public: reset digits cache */
gDigitsCacheManager.cleanCache = function(type, albumIds){
	if (type == "ALL"){
		gDigitsCache = { numAlbums : 0, sortedAlbums: {} };
		return true;
	} else if (type == "ALBUM" && albumIds){
		for (var i=0; i < albumIds.length; i++){
			delete gDigitsCache[albumIds[i]];
			for (var albumType in gDigitsCache.sortedAlbums){
				for (var j=0, lenj = gDigitsCache.sortedAlbums[albumType].length; j < lenj; j++){
					if (gDigitsCache.sortedAlbums[albumType][j] == albumIds[i]){
						gDigitsCache.sortedAlbums[albumType].splice(j,1);
						break;
					}
				}
			}
		}
		return true;
	} else if (type == "DIGITS" && albumIds){
		for (var i=0; i < albumIds.length; i++){
			gDigitsCache[albumIds[i]].digits = {};
			gDigitsCache[albumIds[i]].cache.sortedDigits = {};
		}
		gDigitsCache[albumIds[i]].album.numMedia = 'unknown';
		return true;
	}
	return false;
}

/* Public: get albums from cache */
gDigitsCacheManager.getAlbums = function(albumType){
	var albums = [];
	for (var i=0, leni = gDigitsCache.sortedAlbums[albumType].length; i < leni; i++){
		albums.push(gDigitsCache[gDigitsCache.sortedAlbums[albumType][i]].album);
	}
	return { albumTOList:albums, totalResultsNum:albums.length, statusType:'OK' }
}

/* Public: get digits from cache or send request to get them from server */
gDigitsCacheManager.getDigits = function(albumId, startFrom, numEntities, method){
	var digitsList, recipients;
	if (typeof albumId == 'undefined' || albumId == null){
		digitsList = { digitTOList : [], startFrom : 0, numOfEntities : 0, totalResultsNum : 0, contactUserId : 0 };
	} else {
		var sortKey = this.getSortKey();
		if (!gDigitsCache[albumId]){
			gDigitsCache[albumId] = new albumCacheObject({id : albumId, numMedia : 'unknown'});
		}
		var sortedDigits = gDigitsCache[albumId].cache.sortedDigits;
		var len = null;
		var isBatchFull = true;
		if (gDigitsCache[albumId].album.numMedia == 'unknown'){
			if (numEntities == 'unknown') numEntities = 999;
			this.loadDigits(albumId, startFrom, numEntities, method);
			return;
		} else if (!sortedDigits[sortKey]){
			/*sortedDigits[sortKey] = new PopulatedArray(gDigitsCache[albumId].album.numMedia, null);*/
			sortedDigits[sortKey] = [];
			isBatchFull = false;
		} else {
			/*len = Math.min(startFrom-1+numEntities, sortedDigits[sortKey].length);*/
			if (Math.min(startFrom-1+numEntities, gDigitsCache[albumId].album.numMedia) > sortedDigits[sortKey].length){
				isBatchFull = false;
			} else {
				len = sortedDigits[sortKey].length;				
				for (var i=startFrom-1; i < len; i++){
					try { /* Fix bug 3434, in IE6 an unsprcified error (recurring) is thrown after digit deletion */
						if (!sortedDigits[sortKey][i]){
							isBatchFull = false;
							break;
						}
						// if there are multiple recipients to the digit count as if they were separate digits
						else if (albumId == gSystemLabels.INBOX){
							recipients = gDigitsCache[albumId].digits[sortedDigits[sortKey][i]].recipients;
							/* This check was placed to help handle a server bug.
							 * The server bug has been fixed 
							if (recipients && recipients.length > 0){
								len -= recipients.length - 1;
							}
							*/
						}
					} catch (e) {}
				}
			}
		}
		
		if (!isBatchFull){
			var fullyCachedSortKey = this.findFullyCachedSort(albumId);
			if (fullyCachedSortKey){
				gDigitsCacheManager.currentAlbumId = albumId;
				sortedDigits[sortKey] = $A(sortedDigits[fullyCachedSortKey]);
				sortedDigits[sortKey].sort(gDigitsCacheManager.cmp);
			} else {
				this.loadDigits(albumId, startFrom, numEntities, method);
				return;
			}
		}
		digitsList = {
			digitTOList : [],
			startFrom : startFrom,
			numOfEntities : numEntities,
			totalResultsNum : gDigitsCache[albumId].album.numMedia,
			contactUserId : gDigitsCache[albumId].album.contactUserId,
			labelId : albumId
		};
		//contactUserId:null, userId:gUser.userId, labelId:null
		if (!len) len = Math.min(startFrom-1+numEntities, sortedDigits[sortKey].length);
		for (var i=startFrom-1; i < len; i++){
			digitsList.digitTOList.push(gDigitsCache[albumId].digits[sortedDigits[sortKey][i]]);
		}
	}
	
	var callback;
	for (var i=3; i < CM.methods[method].length; i++){
		try { callback = eval(CM.methods[method][i]); } catch(e){}
		if (callback && callback instanceof Function){
			callback(digitsList);
		}
	}
}

/* Private: load digits */
gDigitsCacheManager.loadDigits = function(albumId, startFrom, numEntities, method){
	var query;
	if (CM.methods[method][1] == 'getConversation'){
		query = this.createConversationQuery(gUser.userId, albumId, gDigitsCacheManager.sortBy, gDigitsCacheManager.sortDir, startFrom, numEntities);
	} else {
		query = this.createDigitsQuery(albumId, gDigitsCacheManager.sortBy, gDigitsCacheManager.sortDir, startFrom, numEntities);
	}
	if (gUserState == "PUBLIC"){
		CM.sendRequest(method, query, gPublicAlbumsUrlInfo.username);
	} else {
		CM.sendRequest(method, query);
	}
}

/* Private: callback for getDigits. inserts digits to cache */
gDigitsCacheManager.cacheDigits = function(digitsList, method){
	var sortKey = gDigitsCacheManager.getSortKey();
	var labelId = digitsList.labelId || digitsList.contactUserId;
	if (!labelId) labelId = (digitsList.labelIds) ? digitsList.labelIds[0] : null;
	if (!labelId) return null;
    if (labelId == gSystemLabels.SENT_ITEMS) labelId = gSystemLabels.INBOX;
    var digitId;
	
	if (gDigitsCache[labelId].album.numMedia == 'unknown'){
		gDigitsCache[labelId].album.numMedia = digitsList.totalResultsNum;
		gDigitsCache[labelId].album.contactUserId = digitsList.contactUserId;
		/*gDigitsCache[labelId].cache.sortedDigits[sortKey] = new PopulatedArray(digitsList.totalResultsNum, null);*/
		gDigitsCache[labelId].cache.sortedDigits[sortKey] = [];
	}
	if (digitsList.digitTOList){
		for (var i=0, len = digitsList.digitTOList.length; i < len; i++){
			digitId = digitsList.digitTOList[i].digitId;
			gDigitsCache[labelId].digits[digitId] = digitsList.digitTOList[i];
			gDigitsCache[labelId].cache.sortedDigits[sortKey][digitsList.startFrom-1+i] = digitId;
		}
	}
	
	// after caching the digits get recall getDigits to get them from cache
	gDigitsCacheManager.getDigits(labelId, digitsList.startFrom, Math.min(digitsList.numOfEntities, digitsList.totalResultsNum), method);
}

/* Public: add new digits to sortedDigits arrays (as result of upload or move to folder */
gDigitsCacheManager.addDigits = function(albumId, digitsList){
	if (!(albumId && digitsList && gDigitsCache[albumId])) return false;
	var totalAdded = 0;	// count how many digits actually added (if only updated en existing digit, it will not be counted)
	gDigitsCacheManager.currentAlbumId = albumId;
	var originalNumMedia = gDigitsCache[albumId].album.numMedia;
	
	// add digit objects to repository
	for (var i=0, leni=digitsList.digitTOList.length; i < leni; i++){
		if (!gDigitsCache[albumId].digits[digitsList.digitTOList[i].digitId]) gDigitsCache[albumId].album.numMedia++;
		gDigitsCache[albumId].digits[digitsList.digitTOList[i].digitId] = digitsList.digitTOList[i];
	}
	
	var sortKey;
	var sortedDigits = gDigitsCache[albumId].cache.sortedDigits;
	// add digits IDs to sorted arrays
	sortKey = this.getSortKey();
	if (!sortedDigits[sortKey]) sortedDigits[sortKey] = [];
	for (var i=0, leni=digitsList.digitTOList.length; i < leni; i++){
		if (!sortedDigits[sortKey].include(digitsList.digitTOList[i].digitId)){
			sortedDigits[sortKey].push(digitsList.digitTOList[i].digitId);
			totalAdded++;
		}
	}
	sortedDigits[sortKey] = sortedDigits[sortKey].sort(gDigitsCacheManager.cmp);
	return totalAdded;
}

/* Public: delete digit objects & IDs from sortedDigits arrays */
gDigitsCacheManager.deleteDigits = function(albumId, arrDigitIds){
	var isDeleted = false;
	if (!(albumId && arrDigitIds && gDigitsCache[albumId])) return false;
	var sortedDigits = gDigitsCache[albumId].cache.sortedDigits;
	for (var i=0, leni=arrDigitIds.length; i < leni; i++){
		// delete digit object
		delete gDigitsCache[albumId].digits[arrDigitIds[i]];
		// delete digit ID from sortedDigits arrays
		for (var sortKey in sortedDigits){
			for (var lenj=sortedDigits[sortKey].length, j=0; j < lenj; j++){
				if (arrDigitIds[i] == sortedDigits[sortKey][j]){
					sortedDigits[sortKey].splice(j, 1);
					gDigitsCache[albumId].album.numMedia--;
					isDeleted = true;
					break;
				}
			}
		}
	}
	return isDeleted;
}

/* Public: move digits from one album to another */
gDigitsCacheManager.moveDigits = function(arrDigitIds, fromAlbum, toAlbum){
	if (!arrDigitIds) return false;
	if (toAlbum && gDigitsCache[toAlbum]){
		var digitsList = { digitTOList : [] };
		for (var i=0, leni=arrDigitIds.length; i < leni; i++){
			digitsList.digitTOList.push(gDigitsCache[fromAlbum].digits[arrDigitIds[i]]);
		}
		this.addDigits(toAlbum, digitsList);
	}
	if (fromAlbum && gDigitsCache[fromAlbum]){ this.deleteDigits(fromAlbum, arrDigitIds); }
	return true;
}

/* Public: set digit caption */
gDigitsCacheManager.setDigitCaption = function(albumId, digitId, caption){
	gDigitsCache[albumId].digits[digitId].digitCaption = caption || '';
}

/* Private: get sort key for sortedDigits array */
gDigitsCacheManager.getSortKey = function(){
	return gDigitsCacheManager.sortBy + "_" + gDigitsCacheManager.sortDir;
}

/* Private: create digits query */
gDigitsCacheManager.createDigitsQuery = function(albumId, sortBy, sortDir, startFrom, numEntities){
	var obj = new Object();
	obj.labelID = albumId;
	obj.digitSortBy = sortBy;
	obj.sortDirection = sortDir;
	obj.from = startFrom;
	obj.numEntities = numEntities;
	obj.calculateTotalFlag = true;
	if (gUserState == "PUBLIC") obj.blockContentFlag = false;
	return obj;
}

/* Private: create conversation query */
gDigitsCacheManager.createConversationQuery = function(userId, contactUserId, sortBy, sortDir, startFrom, numEntities){
	var obj = new Object();
	obj.userId = userId;
	obj.contactUserId = (contactUserId == gSystemLabels.INBOX || contactUserId == gSystemLabels.TRASH) ? null : contactUserId;	// null to get INBOX+SENT_ITEMS or TRASH
	obj.digitSortBy = sortBy;
	obj.sortDirection = sortDir;
	obj.from = startFrom;
	obj.numEntities = numEntities;
	obj.calculateTotalFlag = true;
	if (contactUserId == gSystemLabels.TRASH){
		obj.labelIdSet = [gSystemLabels.TRASH];
	} else {
		obj.labelIdSet = [gSystemLabels.INBOX, gSystemLabels.SENT_ITEMS];
	}
	return obj;
}

/* Private: compare two values (used for sorting digits) */
/* RECEIVED_TIME : 'receivedTime', CAPTION : 'digitCaption', MEDIA_TYPE : 'mediaType', SENDER : 'senderId' */
gDigitsCacheManager.cmp = function(a, b){
	var digits = gDigitsCache[gDigitsCacheManager.currentAlbumId].digits;
	var sortDir = (gDigitsCacheManager.sortDir=='ASC') ? 1 : -1;
	if (gDigitsCacheManager.sortBy == 'CAPTION'){
		a = (digits[a].digitCaption) ? digits[a].digitCaption.toUpperCase() : '';
		b = (digits[b].digitCaption) ? digits[b].digitCaption.toUpperCase() : '';
	} else if (gDigitsCacheManager.sortBy == 'RECEIVED_TIME'){
		a = (digits[a].receivedTime) ? digits[a].receivedTime : '';
		b = (digits[b].receivedTime) ? digits[b].receivedTime : '';
	} else if (gDigitsCacheManager.sortBy == 'MEDIA_TYPE'){
		a = (digits[a].senderId) ? digits[a].mediaType.toUpperCase() : '';
		b = (digits[b].senderId) ? digits[b].mediaType.toUpperCase() : '';
	} else if (gDigitsCacheManager.sortBy == 'SENDER'){
		a = (digits[a].senderId) ? digits[a].senderId.toUpperCase() : '';
		b = (digits[b].senderId) ? digits[b].senderId.toUpperCase() : '';
	}
	return ((b < a) - (a < b)) * sortDir;
}

/* Private: compare two values (used for sorting albums) */
/* CREATION_TIME: 'creationTime', LABEL_NAME: 'name', SHARING_LEVEL: 'shareLevel', ALBUM_SIZE: 'numMedia' */
gDigitsCacheManager.cmpAlbums = function(a, b){
	var sortDir = (gDigitsCacheManager.albumSortDir=='ASC') ? 1 : -1;
	if (gDigitsCacheManager.albumSortBy == 'CREATION_TIME'){
		a = gDigitsCache[a].album.creationTime;
		b = gDigitsCache[b].album.creationTime;
	}
	return ((b < a) - (a < b)) * sortDir;
}

/* Public: set digits sort */
gDigitsCacheManager.setSort = function(sortBy){
	if (sortBy == gDigitsCacheManager.sortBy){
		gDigitsCacheManager.sortDir = (gDigitsCacheManager.sortDir=='ASC') ? 'DESC' : 'ASC';
	} else {
		gDigitsCacheManager.sortBy = sortBy;
		gDigitsCacheManager.sortDir = (sortBy == 'CAPTION') ? 'ASC' : 'DESC';
	}
}

/* Private: find a sortedDigits array that is fully cached or return null */
gDigitsCacheManager.findFullyCachedSort = function(albumId){
	if (typeof gDigitsCache[albumId].album.numMedia == 'undefined'){ return null; }
	var isFullyCached;
	var sortedDigits = gDigitsCache[albumId].cache.sortedDigits;
	for (var sortKey in sortedDigits){
		if (sortedDigits[sortKey].length == gDigitsCache[albumId].album.numMedia) return sortKey;
	}
	return null;
}

/* Public : clone digits, retun them as digitTO list */
gDigitsCacheManager.cloneDigitsAsList = function(albumId, digitIds){
	for (var i=0, arr=[]; i < digitIds.length; i++){
		arr.push(Object.clone(gDigitsCacheManager.getDigitById(albumId, digitIds[i])));
	}
	return { digitTOList : arr };
}

/* Public : get digit by id */
gDigitsCacheManager.getDigitById = function(albumId, digitId){
	return gDigitsCache[albumId].digits[digitId];
}

/*Public : get numMedia for albumId */
gDigitsCacheManager.getNumMedia = function(albumId){
	return (gDigitsCache[albumId] && !isNaN(parseInt(gDigitsCache[albumId].album.numMedia))) ? gDigitsCache[albumId].album.numMedia : 'unknown';
}
/* ======================= */
/* === MENU FUNCTIONS === */
/* ===================== */

/* create digit drop down menu */
function createDigitMenu(){
	if (gDigitMenu) gDigitMenu.remove();
	gDigitMenu = new Menu("digitMenu", "gallery_dropDownMenu", createDigitMenuHeader, createDigitMenuFooter);
	gDigitMenu.setHideCallback(cbOutDigit);
	gDigitMenu.add(TEXT.open, "openMedia()");
	gDigitMenu.add(TEXT.share, "setShareDigit()");
	gDigitMenu.add(TEXT.share, null, "disabled"); // a disabled Share for private albums
	gDigitMenu.add(TEXT.move_to_folder, "void(0)");
	createMoveToFolderMenuSection(gDigitMenu, true);
	if (gAlbumId != gSystemLabels.RECENTLY_RECEIVED){
		gDigitMenu.add(TEXT.set_folder_cover, "preSetAlbumCover()");
		gDigitMenu.add(TEXT.set_folder_cover, null, "disabled"); // a disabled Set as folder cover item for audio & video digits
	}
	gDigitMenu.add(TEXT.delete_media, "openDeleteDigit()");
}

/* create digit sort drop down menu */
function createDigitSortMenu(){
	if (gDigitSortMenu) gDigitSortMenu.remove();
	gDigitSortMenu = new Menu("mDigitSort", "gallery_dropDownMenu narrow", createSortMenuHeader, createSortMenuFooter);
	gDigitSortMenu.add(TEXT.date_1, "setDigitsSortBy('RECEIVED_TIME')");
	gDigitSortMenu.add(TEXT.name_1, "setDigitsSortBy('CAPTION')");
	gDigitSortMenu.add(TEXT.type, "setDigitsSortBy('MEDIA_TYPE')");
	// Bug #2787 fix, add sender to recently received folder
	if (gAlbumId == gSystemLabels.RECENTLY_RECEIVED) {
		gDigitSortMenu.add(TEXT.sender, "setDigitsSortBy('SENDER')");
	}	
}

/* create move to folder drop down menu (in toaster) */
function createMoveToFolderMenu(ignoreCurrentAlbum) {
	if (gMoveToFolderMenu) gMoveToFolderMenu.remove();
	gMoveToFolderMenu = new Menu("mMoveToFolder", "gallery_dropDownMenu", createMoveToFolderMenuHeader, createDigitMenuFooter);
	createMoveToFolderMenuSection(gMoveToFolderMenu, false, ignoreCurrentAlbum);
}

/* create move to folder menu section */
function createMoveToFolderMenuSection(menu, isSubMenu, ignoreCurrentAlbum) {
	if (gDigitsCache.numAlbums == 0) return;
	var albumId, folderClass, func;
	if (isSubMenu) menu.startSubMenu("gallery_dropDownMenu", createDigitSubMenuHeader, createDigitMenuFooter);
	if (gSystemLabels.PLAYLIST) {
		if (gAlbumId == gSystemLabels.PLAYLIST) {
			menu.add(TEXT.music2, "void(0)", 'musicFolderInactive');
		} else {
			menu.add(TEXT.music2, "moveToFolder('"+gSystemLabels.PLAYLIST+"')", 'musicIcon');
		}
	}
	for (var i=0; i < gDigitsCache.sortedAlbums.FOLDER.length; i++) {
		albumId = gDigitsCache.sortedAlbums.FOLDER[i];
		/* Do not add 'My Music to the menu, this is a special case as this is a special */
		if (albumId == gSystemLabels.PLAYLIST) continue;
		
		// Enable ignoring gAlbumId (i.e the current opened album)
		if ((ignoreCurrentAlbum == undefined) && 
			(albumId == gAlbumId || 
			(gAlbumId && gAlbumId == gSystemLabels.PLAYLIST && gDigitsCache[albumId].album.shareLevel == 'PUBLIC'))) {
			folderClass = 'selectedFolder selectedFolderInactive';
			func = 'void(0)';
		} else {
			folderClass = '';
			func = "moveToFolder('"+albumId+"')";
		}
		if (gDigitsCache[albumId].album.shareLevel != 'PUBLIC'){
			if (folderClass) folderClass += ' ';
			if (folderClass.include('selectedFolderInactive')) {
				folderClass += 'privateDropDownLockInactive';
			} else {
				folderClass += 'privateDropDownLock';
			}
		}

		var albumName = gDigitsCache[albumId].album.name;

		if(folderClass.indexOf('privateDropDownLock')!=-1){
			if(albumName.length > 12){
				menu.add(albumName.shorten(12, '...'), func, folderClass, '', albumName);
			}else{
				menu.add(albumName, func, folderClass);
			}
		}else{
			if(albumName.length > 18){
				menu.add(albumName.shorten(18, '...'), func, folderClass, '', albumName);
			}else{
				menu.add(albumName, func, folderClass);
			}
		}
	}
    // Bug #3831 fix, if the current context is from Message History
    // Do not show the 'Create New Album' option
    if (ignoreCurrentAlbum == undefined) {	
	    menu.add(TEXT.create_new_album, "openAddAlbumAndMoveTo()", "createNewAlbum");
    }
    menu.add(TEXT.save_local, "downloadFile()", 'saveLocal');
	if (isSubMenu) menu.endSubMenu();
}

function createMoreSingleMediaMenu(){
	gMoreSingleMediaMenu = new Menu("mSingleMediaMenu", "gallery_dropDownMenu moveto", null, createMoreSingleMediaMenuFooter);
	gMoreSingleMediaMenu.add(TEXT.move_to_folder, "void(0)");
	createMoveToFolderMenuSection(gMoreSingleMediaMenu, true);
	gMoreSingleMediaMenu.add(TEXT.save_local, "downloadFile()");
	gMoreSingleMediaMenu.add(TEXT.delete_media, "openDeleteDigit()");
}

function dummy(){ alert('dummy function'); }

/* mouse over digit */
function overDigit(event){
	if (typeof gDragging == 'undefined' || gDragging) return;
	/* Bug 3435 fix, changed mechanism of object in order to prevent possible */
	/* runtime errors in IE */
	var obj;
	if (document.all) {
		if (event.srcElement.id == '') return;
		obj = $(event.srcElement.id);
	} else {
		obj = event.target;
	}	while (obj && obj.tagName.toLowerCase() != "li"){ obj = obj.parentNode; }
	if (gOverDigit) setDigitOutStyle(gOverDigit);
	changeStyle(obj, 'single_orange_picture');
	gOverDigit = obj;
}

/* mouse out digit */
function outDigit(event){
	if (typeof gDragging == 'undefined' || gDragging) return;
	/* Bug 3435 fix, changed mechanism of object in order to prevent possible */
	/* runtime errors in IE */
	var obj;
	if (document.all) {
		if (event.srcElement.id == '') return;
		obj = $(event.srcElement.id);
	} else {
		obj = event.target;
	}
	while (obj && obj.tagName.toLowerCase() != "li"){ obj = obj.parentNode; }
	if (!isMouseInBounds(obj, event.clientX, event.clientY)){
		setDigitOutStyle(obj);
		gOverDigit = null;
	}
}

/* callback for Menu.hide - does a mouse out digit */
function cbOutDigit(){
	var menuOwner = gDigitMenu.currentOwner;
	while (menuOwner && menuOwner.tagName.toLowerCase() != "li"){ menuOwner = menuOwner.parentNode; }
	if (menuOwner && !isMouseInBounds(menuOwner)){
		setDigitOutStyle(menuOwner);
		gOverDigit = null;
	}
}

/* set menu owner */
function setOwner(event){
	var o = (event.srcElement) ? event.srcElement : event.target;
	gDigitMenu.setOwner(o);
}

/* mouse over digit arrow */
function showDigitMenu(event){
	if (typeof gDragging == 'undefined' || gDragging) return;
	var o = (event.srcElement) ? event.srcElement : event.target;
	gDigitId = getDigitIdFromObjId(o.parentNode.id);
	var digit = getDigitById(gAlbumId, gDigitId);
	var mediaType = digit.mediaType;
	if ((gDigitsCache[gAlbumId].album.shareLevel == 'PRIVATE' && digit.mediaType == 'AUDIO') || digit.contentBlockedFlag == 1){
		hideElement('digitMenu_i2');	// active share
		displayElement('digitMenu_i3');	// disabled share
	} else {
		displayElement('digitMenu_i2');	// active share
		hideElement('digitMenu_i3');	// disabled share
	}
	if (gAlbumId != gSystemLabels.RECENTLY_RECEIVED){
		if (mediaType == 'AUDIO' || mediaType == 'VIDEO'){
			hideElement('digitMenu_i5');	//	active set as folder cover item
			displayElement('digitMenu_i6');	// disabled set as folder cover item
		} else {
			displayElement('digitMenu_i5');	// active set as folder cover item
			hideElement('digitMenu_i6');	// disabled set as folder cover item
		}
	}
	gDigitMenu.show(o, 1, -1, 1, -1);
}

/* mouse out digit arrow */
function hideDigitMenu(event){
	gDigitMenu.hide(event);
}

/* immediatelly hide digit (without timeout) - called when opening dialogs */
function instantHideDigitMenu(){
	if (gDigitMenu && (gDigitMenu.isOverMenu || gDigitMenu.isOverSubMenu)){
		gDigitMenu.isOverMenu = false;
		gDigitMenu._hide(gDigitMenu.id);
	}
}

/* immediatelly hide digit (without timeout */
function instantHideMoveToFolderMenu(){
	if (gMoveToFolderMenu && (gMoveToFolderMenu.isOverMenu || gMoveToFolderMenu.isOverSubMenu)){
		gMoveToFolderMenu.isOverMenu = false;
		gMoveToFolderMenu._hide(gMoveToFolderMenu.id);
	}
	if (gMoreSingleMediaMenu && (gMoreSingleMediaMenu.isOverMenu || gMoreSingleMediaMenu.isOverSubMenu)){
		gMoreSingleMediaMenu.isOverMenu = false;
		gMoreSingleMediaMenu._hide(gMoreSingleMediaMenu.id);
	}
}

/* event listeners for digits */
function addDigitEventListeners(){
	var o = $$('.single_picture');
	o.each(function(el){
		el.observe("mouseover", overDigit, true);
		el.observe("mouseout", outDigit, true);
	});
	o = $$('.orange_arrow');
	o.each(function(el){
		el.observe("mouseover", setOwner, false);
		el.observe("click", showDigitMenu, false);
		el.observe("mouseout", hideDigitMenu, false);
	});
	document.onmousemove = updateMouseXY;
}

/* event listeners for edit move to folder */
function addEditMoveToFolderListeners(){
	var editMoveToFolder = $('editMoveToFolder');
	if (editMoveToFolder){
		editMoveToFolder.observe("click", showMoreSingleMediaMenu, false);
		editMoveToFolder.observe("mouseout", hideMoreSingleMediaMenu, false);
	}
}

/* event listeners for edit move to folder */
function addMoveToFolderListeners(button){
	button = $(button);
	if (button){
		button.observe("click", showMoveToFolderMenu, false);
		button.observe("mouseout", hideMoveToFolderMenu, false);
	}
}

/* check if mouse is inside bounds of obj */
function isMouseInBounds(obj, x, y){
	obj = $(obj);
	if (!obj) return;
	var dimentions = obj.getDimensions();
	var position = Position.cumulativeOffset(obj);
	if (!x) x = gMouseX;
	if (!y) y = gMouseY;
	return (x > position[0] && x < position[0]+dimentions.width && y > position[1] && y < position[1]+dimentions.height);
}

/* track mouse position */
function updateMouseXY(evt){
	if (typeof event != 'undefined') evt = event;	// IE fix
	gMouseX = evt.clientX + document.body.scrollLeft;
	gMouseY = evt.clientY + document.body.scrollTop;
	if (document.all && gOverDigit && gDigitMenu.currentOwner == null && !isMouseInBounds(gOverDigit, gMouseX, gMouseY)){ // IE fix
		setDigitOutStyle(gOverDigit);
		gOverDigit = null;
	}
}

/* show move to folder menu */
function showMoveToFolderMenu(event){
	var o = (event.srcElement) ? event.srcElement : event.target;
	var x = (o.parentNode.parentNode.id == 'playlistMoveToFolder') ? 1 : 2;
	gMoveToFolderMenu.show(o, x, 7, x, 7);
}
/* hide move to folder menu */
function hideMoveToFolderMenu(event){
	gMoveToFolderMenu.hide(event);
}

/* show more actions menu in single media dialog */
function showMoreSingleMediaMenu(event){
	var o = (event.srcElement) ? event.srcElement : event.target;
	gMoreSingleMediaMenu.show(o, 2, 7, 6, 7);
}
/* hide more actions menu in single media dialog */
function hideMoreSingleMediaMenu(event){
	gMoreSingleMediaMenu.hide(event);
}

/* create change recipient menu */
function createChangeRecipientMenu(digit){
	if (gChangeRecipientMenu) gChangeRecipientMenu.remove();
	gChangeRecipientMenu = new Menu("mChangeRecipient", "gallery_dropDownMenu narrow", createSortMenuHeader, createSortMenuFooter);
	for (var i=0; i < digit.recipients.length; i++) {
		gChangeRecipientMenu.add(digit.recipients[i].requestedAddress, "gChangeRecipientMenu.hide();closeDialog();openMessage('0', '" + digit.digitId + "', '" + digit.recipients[i].recipientId + "');");
	}
}
/** ============= */
/** === CROP === */
/** =========== */
var gCropper = null;
var gCroppedImage = null;
var gNumOfDigitsBeforeCrop = null;
var gCroppedTransactionsId = new Array();	// needed for notifications

/* open crop digit */
function openCropPopup(){
	instantHideDigitMenu();
	openDialog('p_crop.html', null, 548, hideCrop, true, 'screen');
	//showCrop(); -> moved to p_crop template
	gCropDigit = new Image();
	var myDigit = getDigitById(gAlbumId, gDigitId);
	gCropDigit.onload = showCrop;
	gCropDigit.src = gAlbumspath+"getImage?mediaLocation=" + myDigit.storageLocation + "&sizeTemplate=DigitFullSize&mediaRadiusAngle=" + myDigit.rotationDegrees;
}

function showCrop(){
	setLoadedDigit('digitImageToCrop', gCropDigit);
	if (gCropper == null){
		var digitImage = $("digitImageToCrop");
		var width = digitImage.clientWidth;
		var height = digitImage.clientHeight;
		var wF = 0.7;  //width factor
		var hF = 0.7;  //Height factor
		var cropWidth = Math.floor(width * wF);
		var cropHeight = Math.floor(height * hF);
		var _x1 = Math.floor((width - cropWidth) / 2);
		var _y1 = Math.floor((height - cropHeight) / 2);
		var _x2 = _x1 + cropWidth;
		var _y2 = _y1 + cropHeight;

		gCropper = new Cropper.Img(
			'digitImageToCrop',
			{
				onEndCrop: onEndCrop,
				displayOnInit: true,
				onloadCoords: { x1: _x1, y1: _y1, x2: _x2, y2: _y2 }
			}
		)
	}
}

function hideCrop(){
	try {
		gCropper.remove();
	} catch(e){}
	gCropper = null;
}

function onEndCrop( coords, dimensions){
	gCroppedImage = {
		x1 : coords.x1,
		y1 : coords.y1,
		x2 : coords.x2,
		y2 : coords.y2,
		width : dimensions.width,
		height : dimensions.height
	}
}

function saveCroppedImage(){
	hideCrop();
	var digit = getDigitById(gAlbumId, gDigitId);
    var transactionId = TransactionId.next();
    gCroppedTransactionsId[transactionId] = gDigitId;
    CM.sendRequest('cropImage$AP',digit.digitId, digit.storageLocation, gCroppedImage.x1, gCroppedImage.y1, gCroppedImage.width, gCroppedImage.height, "SAVE", digit.digitText, gAlbumId, digit.digitCaption, digit.rotationDegrees, transactionId);
	showAfterCropLoader();
}

function saveCroppedImageAs(newName){
	hideCrop();
	closeDialog();
	var digit = getDigitById(gAlbumId, gDigitId);
	var transactionId = TransactionId.next();
//	gCroppedTransactionsId[transactionId] = gDigitId;
	CM.sendRequest('cropImage$AP',digit.digitId, digit.storageLocation, gCroppedImage.x1, gCroppedImage.y1, gCroppedImage.width, gCroppedImage.height, "SAVE_AS", newName, gAlbumId, newName, digit.rotationDegrees, transactionId);
	showAfterCropLoader();
}

function openCropSaveAsDialog(){
	//openDialog("p_save_digit_as.html", null, 227, null, true, 'screen');
	hideElement($$('#cropPicImg div.imgCrop_selArea'));
	displayElement($('save_digit_as'));

}

/* callback for cropImage$AP */
function doCropImage(){
	gCropper = null;
	//todo Orr: at the moment we close the window - later need to update the single media view
	closeAllDialogs();
	backToAlbum();
}
/* show after crop loading message */
function showAfterCropLoader(){
	hideElement('cropDialog');
	displayElement('afterCropDialog');
}

/** =============== */
/** === ROTATE === */
/** ============= */
var gRotatedDigit = null;
/* pre rotate digit */
function preRotateDigit(dir){
	gRotatedDigit = getDigitById(gAlbumId, gDigitId);
	var degrees = (dir == 'left') ? 270 : (dir == 'right') ? 90 : 0;
	gRotatedDigit.rotationDegrees = (gRotatedDigit.rotationDegrees + degrees) % 360;
	CM.sendRequest('updateCabinetDigitHeaders$postRotateDigit', createDigitsOperationQuery([gRotatedDigit], 'UPDATE_OBJECT', gAlbumId));
}
/* callback for updateCabinetDigitHeaders$postRotateDigit - post rotate digit */
function postRotateDigit(){
	var rotateArr = ['digitImage','digitThumb_' + gRotatedDigit.digitId];
	var src = '', el;
	for (var i=0; i < rotateArr.length; i++){
		el = $(rotateArr[i]);
		src = el.src.replace(/&mediaRadiusAngle=[0-9]+/, "&mediaRadiusAngle=" + gRotatedDigit.rotationDegrees);
		el.src = src;
	}
	
	var album = gDigitsCache[gAlbumId].album;
	if (gRotatedDigit.digitId == album.representativeDigitId){
		album.albumRepresentativeDigitRotationDegrees = gRotatedDigit.rotationDegrees;
		var albumMediaCover = $("mediaAlbumCover");
		if (albumMediaCover) albumMediaCover.src = gAlbumspath + 'getImage?mediaLocation=' + album.albumRepresentativeDigitLocation + '&sizeTemplate=AlbumThumbnail&mediaRadiusAngle=' + album.albumRepresentativeDigitRotationDegrees;
	}
	gRotatedDigit = null;
}
/** =========================== */
/** === EDIT DIGIT CAPTION === */
/** ========================= */
/* show rename digit in single view */
function showRenameDigitInSingleView(mediaType){
	makeHidden('dialogsName');
	makeVisible('editDialogsName');
	var dialogBox = Dialog.prototype.openedDialogs[Dialog.prototype.currentInstance].container;
	$('renameCaptionBackgroundLeft').style.left =  '-6px';
	$('renameCaptionBackground').style.left = '4px';
	$('renameCaptionBackground').style.width = (dialogBox.clientWidth -24) + 'px';
	$('renameCaptionBackgroundRight').style.left =  (dialogBox.clientWidth -23) + 'px';
	var editDigitCaptionTxt = $('editDigitCaptionTxt');
	editDigitCaptionTxt.select();
	editDigitCaptionTxt.value = getDigitById(gAlbumId, gDigitId).digitCaption;
	
	/* Ensure that contorls are hidden only of a video is opened */
//	if (mediaType == 'VIDEO') {
//		makeHidden('digitImageControls');
//		makeHidden('imageNav');
//		makeHidden('leftMenu');
//		makeHidden('editPicImg');
//	}
}
/* hide rename digit in single view */
function hideRenameDigitInSingleView(){
	makeHidden('editDialogsName');
	makeVisible('dialogsName');
	makeVisible('digitImageControls');
	makeVisible('imageNav');
	makeVisible('leftMenu');
	var editPicImgObj = $('editPicImg');
	if (editPicImgObj) editPicImgObj.style.visibility = 'inherit';
}

/* create digit caption editor */
function createDigitCaptionEditor(digitId){
	var data = TM.loadAndParse('p_digit_caption_editor.html', { digitId : digitId });
	var captionEditor = document.createElement('div');
	captionEditor.className = 'editDigitCaptionLayer';
	captionEditor.id = 'captionEdit' + digitId;
	captionEditor.innerHTML = data;
	var digitCont = $('digit_'+digitId);
	digitCont.appendChild(captionEditor);
}
/* show digit caption editor */
function showDigitCaptionEditor(obj, digitId){
	if (gDragging) return;
	if (gCaptionEditorShowing) closeDigitCaptionEditor(gCaptionEditorShowing);
	if ($('captionEditText_' + digitId)){
		displayElement('captionEdit' + digitId);
	} else {
		createDigitCaptionEditor(digitId);
	}
	gDigitId = digitId;
	var captionEditText = $('captionEditText_' + digitId);
	captionEditText.value = obj.innerHTML;
	captionEditText.focus();
	captionEditText.select();
	gCaptionEditorShowing = digitId;
}
/* close digit caption editor */
function closeDigitCaptionEditor(digitId){
	var captionEditText = $('captionEditText_' + digitId);
	if (captionEditText){
		captionEditText.value = '';
		captionEditText.blur();
	}
	hideElement('captionEdit' + digitId);
	gCaptionEditorShowing = false;
}
/* save digit caption */
function saveDigitCaption(digitId, from){
	var val = (from == 'album') ? $I('captionEditText_' + digitId) : $I('editDigitCaptionTxt');
	val = val.strip().stripScripts().stripTags();
	if (val == '') return;
	
	gDigitsCacheManager.setDigitCaption(gAlbumId, digitId, val);
//	CM.sendRequest('updateDigitCaption$AP',digitId, val);
	var digit = gDigitsCacheManager.getDigitById(gAlbumId, digitId);
	CM.sendRequest('updateCabinetDigitHeaders$updateDigitCaption', createDigitsOperationQuery([digit], 'UPDATE_OBJECT'));
	
	if (from == 'album'){
		closeDigitCaptionEditor(digitId);
		$('digitCaption_'+gDigitId).innerHTML = val;
	} else {
		hideRenameDigitInSingleView();
		$('editPicName').innerHTML = val;
	}
}

/* set previous thumb in single media view */
function setPrevThumb(){
	var prevPic = $('prevPic');
	if (prevPic) setThumb(prevPic, gPrevDigitId);
}
/* set next thumb in single media view */
function setNextThumb(){
	var nextPic = $('nextPic');
	if (nextPic) setThumb(nextPic, gNextDigitId);
}
/* set thumb in single media view */
function setThumb(pic, digitId){
	var digit = getDigitById(gAlbumId, digitId);
	pic.src = gAlbumspath+'getImage?mediaLocation='+digit.storageLocation+'&sizeTemplate=nextPrevThumbnail&mediaRadiusAngle='+digit.rotationDegrees;
}

/* get sorted digits array */
function getSortedDigitsList(albumId){
	return gDigitsCache[albumId].cache.sortedDigits[gDigitsCacheManager.getSortKey()];
}

/* get digit by id */
function getDigitById(albumId, digitId){
	return gDigitsCache[albumId].digits[digitId];
}

/* get previous or next digit relative to current digit id */
function getAdjacentDigitIdById(albumId, digitId, distance){
	var sortedDigits = getSortedDigitsList(albumId);
	for (var i=0, leni=sortedDigits.length; i < leni; i++){
		if (sortedDigits[i] == digitId){
			return sortedDigits[(i + leni + distance) % leni];
		}
	}
	return null;
}

/* get position of digit in album at current sort */
function getDigitPosition(albumId, digitId){
	var sortedDigits = getSortedDigitsList(albumId);
	for (var i=0, leni=sortedDigits.length; i < leni; i++){
		if (sortedDigits[i] == digitId){
			return i + 1;
		}
	}
	return null;
}

/* get digit's sender name or address */
function getSenderName(digit){
	if (digit.senderNickname) return digit.senderNickname;
	var contact = getContactTOById(digit.senderId);
	if (!contact) return '';
	return contact.username || contact.addresses.mobile || contact.addresses.email || '';
}

/* set img src in single view */
function setSingleViewImg(){
	setLoadedDigit('digitImage', gEditDigit);
}/* === GLOBAL VARIABLES === */

/* data holders */
var gUserContactTOs = null;
var gUserCommunicationAddresses = null;
var gUserContactsList = null;	// this var will hold both user nickname & address
var gUserContactsAddressList = null;
var gUserContactsDisplayList = null;
var gUserContactsDisplayListMemberTypein = null;
var gUserContactsId2IndexMapping = {};

var gSelectedFriends = [];
var gSelectedContacts = [];
var gSliders = {};

var gDeleteContactsCounter = 0;
var gTotalContactsCount = 0;
var gTotalContactsCountAfter = 0;
var gSendingFileFromFS = false;
var gMessageSendMethod = 'sendDigit$AP';	// default - for sending text only
var gDisplayedContactTabContainer = 'friends';
var gComposerAutoCompleter = null;
var gIsContactsToasterShowing = false;
var gNotification = null;

var gSearchFriends = null;
var gIsQuickSearchFriendsShowing = false;

var gLastUpdatedFriendNickname = '';
var gLastUpdatedMobile = '';
var gLastUpdatedEmail = '';

/* callback for getUserContactsTOs$AP */
function updateUserContactTOs(contactTOs) {
    gUserContactTOs = contactTOs;
    if (gUserCommunicationAddresses && gCountryCode) {    // if already got communication addresses from dwr & country code from login response
        createContactsList(renderMessagesColumn);
    }
}

/* callback for getUserCommunicationAddressTOs$AP */
function updateUserCommunicationAddresses(communicationAddresses) {
    gUserCommunicationAddresses = uniqContactTOs(communicationAddresses);
    if (gUserContactTOs && gCountryCode) {    // if already got contactTOs from dwr & country code from login response
        createContactsList(renderMessagesColumn);
    }
}

/* unify gUserCommunicationAddresses & gUserContactTOs into gUserContactsList */
function createContactsList(callback) {
    var userCommunicationAddresses = uniqContactTOs(gUserCommunicationAddresses);
    /* Ensure no diplicates are found */
    gUserContactsList = [];
    gUserContactsId2IndexMapping = {};
    gUserContactsAddressList = [];
    gUserContactsDisplayList = [];
    gUserContactsDisplayListMemberTypein = [];

    var addressType, contact, address, name, flagForMe;
    for (var j = 0, lenj = gUserContactTOs.length; j < lenj; j++) {
        if (!gUserContactTOs[j].member) {
            gUserContactTOs[j].nickname = mobileToLocal(gUserContactTOs[j].nickname);
        }
        gUserContactsList[j] = {
            contactUserId : gUserContactTOs[j].contactUserId,
            username : gUserContactTOs[j].username,
            nickname : gUserContactTOs[j].nickname,
            member : gUserContactTOs[j].member,
            blocked : gUserContactTOs[j].blocked,
            userState : gUserContactTOs[j].userState,
            addresses : {}
        };
        gUserContactsId2IndexMapping[gUserContactsList[j].contactUserId] = j;
    }
    for (var i = 0, leni = userCommunicationAddresses.length; i < leni; i++) {
        address = userCommunicationAddresses[i].address;
        addressType = (isEmail(address)) ? 'email' : 'mobile';
        if (addressType == 'mobile') address = mobileToLocal(address);
        contact = getContactTOById(userCommunicationAddresses[i].contactUserId);
        contact.addresses[addressType] = address;
        if (contact.member) {
            if (contact.contactUserId != gUser.userId) {
                gUserContactsAddressList.push(contact.username);
            }
        } else {
            gUserContactsAddressList.push(address);
        }
        // build gUserContactsDisplayList & gUserContactsDisplayListMemberTypein
        addContactToAutoCompleteList(contact, address);
    }

    // todo: remove insertion of member email when server returns this data
    for (var i = 0, leni = gUserContactsList.length; i < leni; i++) {
        addMemberEmailAddress(gUserContactsList[i]);
    }
    addMeAsContactToAutoCompleter();
    if (gUserState == "PRIVATE" && callback) callback();
}

/* Bug 3695 fix solution. Let the autocompleter and   */
/* the rest of the lists load up and add the 'Me' and */
/* the username after the dust have settled down */
function addMeAsContactToAutoCompleter() {
    /* Add owner phone number to the auto-complete list */
    var meAsContact = {
        blocked : false,
        communicationAddresses : null,
        contactUserId : gUser.userId,
        member : true,
        nickname : gUser.nickname,
        privilegeMask : 2,
        userState : 'ACTIVE_MEMBER',
        username : gUser.username,
        addresses : {}
    }

    /* Set 'Me' address */
    for (var i = 0, leni = gUser.userTO.communicationAddresses.length; i < leni; i++) {
        address = gUser.userTO.communicationAddresses[i].communicationAddress;
        addressType = (isEmail(address)) ? 'email' : 'mobile';
        meAsContact.addresses[addressType] = address;
        if (address == 'mobile') break;
    }
    gUserContactsAddressList.push(meAsContact.username);
    addContactToAutoCompleteList(meAsContact, address);
    meAsContact.username = TEXT.me;
    gUserContactsAddressList.push(TEXT.me);
    addContactToAutoCompleteList(meAsContact, address);
}

/* render messages column (in this order: composer, Activity monitor) */
function renderMessagesColumn() {
    if (!gMessageComposer) {
        gMessageComposer = TM.loadAndParse('messageComposer.html', null, 'messageComposer');
        setDroppable();
        setInputsAsUnDroppable();
        setQuickMessageAutoComplete();
    }
    if (!gActivityMonitor) {
        initActivityMonitor();
    }
}

/* render contact panels */
function renderContactPanels() {
    gContactsBlock = TM.loadAndParse('contacts_pane.html', null, 'contactsContainer');
}

/* create Contact object */
function Contact(contactId, nickname, addresses) {
    if (!contactId) contactId = null;
    if (!nickname) nickname = '';

    this.blocked = false;
    this.clientExtra = null;
    this.contactId = contactId;
    this.id = null;
    this.nickname = nickname;
    this.privilegeMask = 2;
    this.userId = gUser.userId;
    this.socialContexts = [];
    var len;
    for (var i = 0; i < addresses.length; i++) {
        if (!addresses[i]) continue;
        len = this.socialContexts.length;
        this.socialContexts[len] = {};
        this.socialContexts[len].contactId = this.contactId;
        this.socialContexts[len].value = isEmail(addresses[i]) ? addresses[i] : validateNumber(addresses[i]);
        this.socialContexts[len].socialContextType = getContactType(addresses[i]).toUpperCase();
    }
    return this;
}

/* get contact object from gUserContactsList by contact id */
function getContactTOById(id) {
    return gUserContactsList[gUserContactsId2IndexMapping[id]] || null;
}

/* get contact object from gUserContactTOs */
function getUserContactTOIndexById(id) {
    for (var i = 0, leni = gUserContactTOs.length; i < leni; i++) {
        if (gUserContactTOs[i].contactUserId == id) return i;
    }
    return null;
}

/* update an address in gUserCommunicationAddresses */
function updateCommunicationAddress(id, type, address) {
    for (var i = 0, leni = gUserCommunicationAddresses.length; i < leni; i++) {
        if (gUserCommunicationAddresses[i].contactUserId == id && type == getContactType(gUserCommunicationAddresses[i].address)) {
            gUserCommunicationAddresses[i].address = address;
            return;
        }
    }
    gUserCommunicationAddresses.push({contactUserId:id, address:address});
}

/* add contact to auto-complete list */
function addContactToAutoCompleteList(contact, address) {
    var name;
    if (!isEmail(address)) {
        address = mobileToLocal(address);
    }
    if (contact.member) {
        name = contact.username || contact.nickname;
        name = (name) ? name + ' ' : '';
        gUserContactsDisplayList.push(name + '&lt;' + address + '&gt;');
        gUserContactsDisplayListMemberTypein.push(name);
    } else {
        if (contact.nickname != '') {
            gUserContactsDisplayListMemberTypein.push(contact.nickname);
        } else {
            gUserContactsDisplayListMemberTypein.push(address);
        }
        gUserContactsDisplayList.push(address);
    }
    if (gComposerAutoCompleter) {
        gComposerAutoCompleter.options.array = gUserContactsAddressList;
        gComposerAutoCompleter.options.displayArray = gUserContactsDisplayList;
    }
}

function addMemberEmailAddress(contact) {
    if (contact.member && !contact.addresses.email) {
        var memberEmail = contact.username + '@' + gMAIL.replace(/\:\d+$/, '').replace(/^www\./, '');
        contact.addresses['email'] = memberEmail;
        //gUserContactsAddressList.push(contact.username);
        var name = contact.nickname || contact.username;
        name = (name) ? name + ' ' : '';
        gUserCommunicationAddresses.push({contactUserId:contact.contactUserId, address:memberEmail});
    }
}

/* slider data object */
function sliderData(container, handle, slider, scrollAmount) {
    this.container = container;
    this.handle = handle;
    this.slider = slider;
    this.scrollAmount = scrollAmount;
    return this;
}

/* create slider */
function createSlider(container, track, handle) {
    container = $(container);
    if (!container) return;
    /* IE does not calculate the correct scrollHeight the first time it is accessed
     so we'll use a dummy variable here so in the next line it is calculated correctly  */
    var IEscrollHeightFix = container.scrollHeight - container.offsetHeight;
    var scrollAmount = container.scrollHeight - container.offsetHeight;
    if (scrollAmount > 0) {
        var sliderHandle = $(handle);
        var sliderHeight = Math.round(container.offsetHeight * (container.offsetHeight / container.scrollHeight));
        sliderHeight = (sliderHeight < 10) ? 10 : sliderHeight;
        sliderHandle.style.height = sliderHeight + 'px';
        // create slider
        displayElement(track);
        if (gSliders[track]) {
            gSliders[track].slider.dispose();
            gSliders[track].slider = null;
            gSliders[track] = null;
        }
        var slider = new Control.Slider(handle, track, {
            axis:'vertical',
            onSlide:function (value, el) {
                var trackId = el.track.id;
                try {
                    gSliders[trackId].container.scrollTop = Math.round(value * gSliders[trackId].scrollAmount);
                } catch (e) {
                }
            },
            onChange:function (value, el) {
                var trackId = el.track.id;
                try {
                    gSliders[trackId].container.scrollTop = Math.round(value * gSliders[trackId].scrollAmount);
                } catch (e) {
                }
            }
        });
        gSliders[track] = new sliderData(container, sliderHandle, slider, scrollAmount);
        slider.setValue(0);
    } else {
        hideElement(track);
    }
}

/* clear selected friends from my friends box */
function clearSelectedFriends() {
    var quickMessageTo = $('quick_message_to');
    setDeafultMessage(quickMessageTo, false, TEXT.friend_mobile_number);
    setTextAlign(quickMessageTo, TEXT.friend_mobile_number);
    var friendsTab = $('friendsTab');
    if (!friendsTab) return;
    var friendsList = friendsTab.getElementsByTagName('div');
    for (var i = 0, leni = friendsList.length; i < leni; i++) {
        if (friendsList[i].className != '') {
            friendsList[i].className = '';
        }
    }
    gSelectedFriends = [];
}

/* clear composer */
function clearComposer() {
    $('uploadToMessage').form.reset();
    clearSelectedFriends();
    var quickMessage = $('quick_message');
    quickMessage.value = '';
    setDeafultMessage(quickMessage, false, TEXT.type_your_message_here);
    setTextAlign(quickMessage, TEXT.type_your_message_here);
    removeMediaFromQuickMessage();
    gSendingFileFromFS = false;
    //	$('uploadToMessage').value = '';
}

function clearMessageTo() {
    var quickMessageTo = $('quick_message_to');
    if (quickMessageTo.value == TEXT.friend_mobile_number) {
        quickMessageTo.value = '';
    }
}

/* check whether to hilite or lowlite a friend when typing addresses into composer */
// todo orr: function needs revision due to UI changes
function checkHiliteFriend() {
    var friendsTab = $('friendsTab');
    if (!friendsTab) return;
    var composerAddresses = $('quick_message_to').value;
    var friendsDivs = friendsTab.getElementsByTagName('div');
    var address = null;
    var spans = null;
    var isMatch;
    var regEx;
    for (var i = 0, leni = friendsDivs.length; i < leni; i++) {
        spans = friendsDivs[i].getElementsByTagName('span');
        if (spans.length == 0) continue;
        address = (spans.length > 1) ? spans[1].innerHTML : spans[0].innerHTML;
        address = address.replace(/\./g, "\\.");
        regEx = eval('/\W?' + address + '\W?/');
        isMatch = regEx.test(composerAddresses);
        // todo orr: change to new class name
        if (friendsDivs[i].className == 'selected' && !isMatch) {
            friendsDivs[i].className = '';
        } else if (friendsDivs[i].className != 'selected' && isMatch) {
            friendsDivs[i].className = 'selected';
        }
    }
}

/* mouse over contact */
function overContact(node) {
    changeStyle(node, 'contactListHover');
}
/* mouse out contact */
function outContact(node) {
    var contactId = node.id.substring(node.id.lastIndexOf('_') + 1);
    var clss = (gSelectedFriends.include(contactId)) ? 'contactListSelected' : '';
    changeStyle(node, clss);
}

/* close delete toaster */
function closeDeleteToaster() {
    gSelectedFriends = [];
    Effect.BlindUp('controlPanel_top', {duration:.3})
    var contactsList = $(gDisplayedContactTabContainer + 'Tab').getElementsByTagName('div');
    for (var i = 0, leni = contactsList.length; i < leni; i++) {
        if (contactsList[i].className != '') contactsList[i].className = '';
    }
}

/* select quick contact */
function selectFriend(node, event, contactId) {
    while (node && node.tagName.toLowerCase() != 'div') {
        node = node.parentNode;
    }
    var quickMessageTo = $('quick_message_to');
    node.blur();

    var contact = getContactTOById(contactId);
    var address = (contact.member) ? contact.username : contact.addresses.mobile || contact.addresses.email;

    if (event.ctrlKey) {
        if (gSelectedFriends.include(contactId)) {
            gSelectedFriends = gSelectedFriends.without(contactId);
            quickMessageTo.value = quickMessageTo.value.replace(address + ',', '');
            if (gSelectedFriends.length == 0) {
                Effect.BlindUp('controlPanel_top', {duration:.3});
                gIsContactsToasterShowing = false;
            }
        } else {
            if (gSelectedFriends.length == 0) {
                gSelectedFriends = [contactId];
                quickMessageTo.value = address + ',';
            } else {
                gSelectedFriends.push(contactId);
                quickMessageTo.value += address + ',';
            }
            if (!gIsContactsToasterShowing) {
                Effect.BlindDown('controlPanel_top', {duration:.3});
                gIsContactsToasterShowing = true;
            }
            makeElBlink('quick_message_to');
        }
        /* Also collect names for potential deletion operation */
        if (gSelectedContacts.include(contactId)) {
            gSelectedContacts = gSelectedContacts.without(contactId);
        } else { /* If the contact Id is not already selected add it*/
            gSelectedContacts.push(contactId);
        }
    } else {
        if (gIsContactsToasterShowing) {
            Effect.BlindUp('controlPanel_top', {duration:.3});
            gIsContactsToasterShowing = false;
        }
        gSelectedFriends = [contactId];
        quickMessageTo.value = address + ',';
        var contactsList = $$('#friendsTab div');
        for (var i = 0, leni = contactsList.length; i < leni; i++) {
            contactsList[i].removeClassName('contactListSelected');
        }
        makeElBlink('quick_message_to');
    }

    if (quickMessageTo.value == '') {
        setDeafultMessage(quickMessageTo, false, TEXT.friend_mobile_number);
    }
    setTextAlign($('quick_message_to'), TEXT.friend_mobile_number);
}

/* filter contacts */
function filterContacts(field) {
    var txt = field.value.toLowerCase();
    var container = $(gDisplayedContactTabContainer + 'Tab');
    var contactsList = container.getElementsByTagName('div');
    var contactElement, contactId, contact, contactDetails, mobile;
    for (var k = 0, lenk = contactsList.length; k < lenk; k++) {
        contactElement = contactsList[k];
        if (txt == '') {
            displayElement(contactElement);
            continue;
        }
        contactId = contactElement.id.split('_')[1];
        contact = getContactTOById(contactId);
        if (!contact) {
            continue;
        }
        contactDetails = [];
        if (contact.nickname) contactDetails.push(contact.nickname);
        if (contact.username) contactDetails.push(contact.username);
        mobile = mobileToLocal(contact.addresses.mobile);
        if (mobile) contactDetails.push(mobile);
        if (contact.addresses.email) contactDetails.push(contact.addresses.email);

        contactElement.style.display = contactDetails.any(function(detail) {
            return detail.toLowerCase().indexOf(txt) == 0;
        }) ? 'block' : 'none';
    }
}

/* filter quick contacts */
function filterQuickContacts(field) {
    var txt = field.value.toLowerCase();
    var quickContactsList = $('searchFriendsList').getElementsByTagName('span');
    var li;
    for (var i = 0, leni = quickContactsList.length; i < leni; i++) {
        li = quickContactsList[i].parentNode.parentNode;
        if (txt == '') {
            displayElement(li);
            continue;
        }
        li.style.display = (quickContactsList[i].innerHTML.toLowerCase().indexOf(txt) == 0) ? 'block' : 'none';
    }
    createSlider('searchFriendsListCont', 'quickFriendsSliderTrack', 'quickFriendsSliderHandle');
}

function addcomma() {
    var field = (gUserState == "PRIVATE") ? 'quick_message_to' : 'share_address';
    $(field).value += ',';
}

/* set quick message auto complete */
function setQuickMessageAutoComplete() {
    gComposerAutoCompleter = new Autocompleter.Local('quick_message_to', 'quick_message_address_list', gUserContactsAddressList,
    {
        tokens:',',
        choices : 100,
        partialChars : 1,
        afterUpdateElement:addcomma,
        fullSearch:true,
        partialSearch:true,
        displayArray:gUserContactsDisplayList
    });
}
/* change between autocomplete lists based on first character typed */
function setAutoCompleteList(field) {
    var value = field.value;
    if (value == '' || !gComposerAutoCompleter) return;
    gComposerAutoCompleter.options.displayArray = (isNaN(value.charAt(0))) ? gUserContactsDisplayListMemberTypein : gUserContactsDisplayList;
}

/* open delete contacts dialog */
function openDeleteContacts(node, contactId) {
    gSelectedFriends = [];
    /* Clear selected friends, if the user has selected deletion */
    if (contactId) gSelectedContacts.push(contactId);
    if (gSelectedContacts.length == 0) return;
    var dialogWidth = (gLang == 'de') ? 266 : 233;
    if (gSelectedContacts.length == 1) node = node.parentNode.parentNode.parentNode;
    openDialog('contacts_delete.html', null, dialogWidth, closeDeleteContacts, null, null, null, null, node, 25, 44);
}
/* callback for close delete contacts dialog */
function closeDeleteContacts() {
    gSelectedContacts = [];
}

/* sets flag for adding file from FS in composer */
function setAddFileFromFS() {
    removeMediaFromQuickMessage();
    gSendingFileFromFS = true;
    var filename = $('uploadToMessage').value;
    var spaceInjectedFilename = '';

    spaceInjectedFilename = breakString(filename, 10, 'floatL');
    setDragMediaHereTitle(spaceInjectedFilename, 'left');
}

function isLegalExt() {
    var extArray = ['.jpg','.jpe','.jpeg','.gif','.png','.bmp','.mpg','.mpeg','.mpe','.wmv','.avi','.mp4'];
    var uploadToMessage = $('uploadToMessage');
    if (!uploadToMessage) return false;
    uploadToMessage = uploadToMessage.value.toLowerCase();
    for (var i = 0; i < extArray.length; i++) {
        if (uploadToMessage.indexOf(extArray[i]) > 0) {
            return true;
        }
    }
    openDialog('p_error.html', {error:TEXT.unSupported_file_type}, 280);
    return false;
}

/***********************************
 send quick message functions
 *********************************/

function openAddRecipientsDialog() {
    openDialog('p_error.html', {error:TEXT.add_recipients, showButton:true, buttonText:TEXT.ok}, 300, null, null, null, null, null, $('messageComposer'), 20, 0);
}

function emailCheckForCredits(recipients) {
    var flag = false;
    var recipientsFld = [];
    for (var i = 0, leni = recipients.length; i < leni; i++) {
        if (recipients[i].recipientType == 'EMAIL') {
            flag = true;
            recipientsFld.push(recipients[i].recipientId, '~', recipients[i].recipientType, '~', recipients[i].requestedAddress, ',');
        }
    }
    if (!flag) {
        clearComposer();
        return false;
    } else {
        recipientsFld.pop();
        return recipientsFld.join('');
    }
}


function sendQuickMessage() {
    var recipients = $('quick_message_to').value;
    if (recipients == TEXT.friend_mobile_number || recipients.trim() == '') {
        openAddRecipientsDialog();
        return;
    }

    if (recipients.split(",").length > 10) {
        openDialog('p_error.html', {error:TEXT.ten_messages_limit, showButton:true, buttonText:TEXT.ok}, 300, null, null, null, null, null, $('messageComposer'), 20, 0);
        return false;

    }

    recipients = createRecipientsFromQuery('quick_message_to');
    if (recipients == null) {
        return;
    } else {
        if (recipients.length == 0) {
            openAddRecipientsDialog();
            return;
        }
    }

    var msg = $('quick_message').value;
    if (msg == TEXT.type_your_message_here) {
        msg = '';
    }
    if (!msg && !gAttachmentType && !gSendingFileFromFS) return;
    var checkCredits = gNotifications.maxedOut || $I("credits").match(/ 0 /);
    // send link to album or zone
    if (gSendingFileFromFS) {
        if (!isLegalExt()) {
            return;
        }
        var recipientsFld = [];
        var finalRecipients = "";
        if (checkCredits) {
            var result = emailCheckForCredits(recipients);
            if (!result) {
                return false;
            } else {
                finalRecipients = result;
            }
        } else {
            for (var i = 0, leni = recipients.length; i < leni; i++) {
                recipientsFld.push(recipients[i].recipientId, '~', recipients[i].recipientType, '~', recipients[i].requestedAddress, ',');
            }
            recipientsFld.pop();
            finalRecipients = recipientsFld.join('');
        }

        $('recipients').value = finalRecipients;
        var composerForm = $('composerForm');
        composerForm.action = gAlbumspath + 'upload.form';
        if ($('quick_message').value == TEXT.type_your_message_here) {
            $('quick_message').value = '';
        }
        composerForm.submit();
        showSentMessageDialog();
    }
    else
    {
        if (checkCredits) {
            var result = emailCheckForCredits(recipients);
            if (!result) {
                return false;
            }
        }
        switch (gMessageSendMethod) {
            case 'sendDigit$AP':
                CM.sendRequest(gMessageSendMethod, gAttachmentAlbumId, gAttachmentDigitId, recipients, msg, TransactionId.next());
                break;

            case 'forwardDigit$AP':
                CM.sendRequest(gMessageSendMethod, gAttachmentAlbumId, gAttachmentDigitId, recipients, msg, TransactionId.next());
                break;

            case 'shareLink$AP':
                var shareAreaTO = new Object();
                shareAreaTO.userName = gUser.username;
                shareAreaTO.albumId = gAttachmentAlbumId;
                shareAreaTO.digitId = gAttachmentDigitId;
                shareAreaTO.shareArea = gAttachmentType;
                CM.sendRequest(gMessageSendMethod, recipients, msg, shareAreaTO, TransactionId.next());
                break;

            case 'forwardFromBackPack$AP':
                var username = gPublicUser.username || gUser.username;
                CM.sendRequest(gMessageSendMethod, gAttachmentDigitId, recipients, msg, username, TransactionId.next());
                break;
        }
    }
}

/* remove media from quick message */
function removeMediaFromQuickMessage() {
    gAttachmentType = null;
    gAttachmentAlbumId = null;
    gAttachmentDigitId = null;
    gMessageSendMethod = 'sendDigit$AP';
    setDragMediaHereTitle(TEXT.drag_media_here);
    hideElement('dragMediaItemsArea', 'dragZone', 'dragFolder', 'dragDigit');
}

function setDragMediaHereTitle(title, align) {
    var DragMediaHereTitle = $('DragMediaHereTitle');
    if (!DragMediaHereTitle) return;
    DragMediaHereTitle.style.textAlign = align || 'center';
    DragMediaHereTitle.innerHTML = title;
}

/* get contacts type */
function getContactType(address) {
    return (isEmail(address)) ? "email" : "mobile";
}

function validateContactDetails(nickname, addresses) {
    var errMsg = '';
    var alphaNumExp = /^[0-9a-zA-Z]+$/;
    var alphaExp = /^[a-zA-Z]/;
    if (nickname != null) {
        nickname = nickname.strip().stripScripts().stripTags();
        if (!$N(nickname) || nickname == TEXT.friend_name) {
            errMsg = TEXT.friend_name_cannot_be_empty;
        } else if (nickname.length < 6 || nickname.length > 12) {
            errMsg = TEXT.username_length_bad;
        }
        /*else if (!nickname.match(alphaNumExp)){
         errMsg = TEXT.username_english;
         }else if (!nickname.match(alphaExp)){
         errMsg = TEXT.username_letter;
         }*/
    }
    addresses.each(function(iterator) {
        return iterator.strip().stripScripts().stripTags();
    });
    var foundValidAddress = false;
    for (var i = 0, leni = addresses.length; i < leni; i++) {
        if (!$N(addresses[i])) {
            if (i == leni - 1 && !foundValidAddress) errMsg += TEXT.friend_email_or_mobile;
        } else {
            var validAddress = (addresses[i].indexOf('@') != -1) ? isEmail(addresses[i]) : validateNumber(addresses[i]);
            if (!validAddress) {
                errMsg = TEXT.friend_incorrect;
            } else {
                foundValidAddress = true;
            }
        }
    }
    return errMsg;
}

/* check mobile number in add friend dialog */
function addFriendCheckMobile(node) {
    if (validateNumber(node.value) || node.value == '') {
        hideElement('addFriend_mobile_error');
    } else {
        displayElement('addFriend_mobile_error');
    }
}
/* check email in add friend dialog */
function addFriendCheckEmail(node) {
    if (isEmail(node.value) || node.value == '') {
        hideElement('addFriend_email_error');
    } else {
        displayElement('addFriend_email_error');
    }
}

/* when adding a new contact, check by mobile number if contact is a member */
function isNumberRegisteredOnAddContact() {
    var mobile = validateNumber($('addFriend_mobile').value);
    if (mobile) {
        CM.sendRequest('isNumberRegistered$addContact', mobile);
    } else {
        addContact(false);
    }
}
/* add contact */
function addContact(isRegistered) {
    var nickname = $I('addFriend_name');
    var mobile = $I('addFriend_mobile');
    var email = $I('addFriend_email');
    var errMsg = validateContactDetails(null, [mobile, email]);
    if (errMsg != '') {
        var parentDialog = Dialog.prototype.openedDialogs[Dialog.prototype.currentInstance];
        openDialog('p_error.html', {error:errMsg}, 250, null, true, null, null, null, parentDialog.container, 0, 30);
        return;
    }
    if (isRegistered) {
        var contact = new Contact(null, nickname, [mobile, email]);
        CM.sendRequest('contactUpdateRequest$add', contact, "CREATE_OBJECT");
    } else {
        if (mobile) {
            var contact = new Contact(null, nickname, [mobile]);
            CM.sendRequest('contactUpdateRequest$add', contact, "CREATE_OBJECT");
        }
        if (email) {
            var contact = new Contact(null, nickname, [email]);
            CM.sendRequest('contactUpdateRequest$add', contact, "CREATE_OBJECT");
        }
    }
}

/* callback for contactUpdateRequest$add */
function doAddContact() {
    $I('addFriend_name', '');
    $I('addFriend_mobile', '');
    $I('addFriend_email', '');
    closeDialog();
    setFeedbackMessage('feedbackMessage', TEXT.contact_information_saved, true, 5000);
}

/* Called from notification after a user has been added*/
function updateContactNotification(userObject) {
    var nickname = gLastUpdatedFriendNickname // Since server returns the nickname with a defualt value
    var mobile = gLastUpdatedMobile;
    var email = gLastUpdatedEmail;

    // Now add the newly created user to the global
    // user contacts list
    gUserContactsList[gUserContactsList.length] = {
        contactUserId : userObject.id,
        username : userObject.username,
        nickname : nickname,
        member : userObject.member,
        blocked : false,
        userState : userObject.userState,
        addresses : userObject.communicationAddresses
    };

}

/* update contact */
function updateContact() {
    var id = $('editContactId').value;
    var contact = getContactTOById(id);
    var nickname = $I('editContactName');
    if (nickname == contact.username || contact.member) nickname = null;
    var arr = [];
    var mobile = $I('editContactMobile');
    if (mobile != $N(contact.addresses.mobile, '')) arr.push(mobile);
    var email = $I('editContactEmail');
    if (email != $N(contact.addresses.email, '')) arr.push(email);
    var errMsg = validateContactDetails(nickname, arr);
    if (errMsg != '') {
        openDialog('p_error.html', {error:errMsg}, 414);
        return;
    }
    removeContactFromLists(contact.contactUserId);
    var contactObj = new Contact(id, nickname, [mobile, email]);
    CM.sendRequest("contactUpdateRequest$update", contactObj, "UPDATE_OBJECT");
}
/* callback for contactUpdateRequest$update */
function doUpdateContact() {
    closeDialog();
    setFeedbackMessage('feedbackMessage', TEXT.contact_information_saved, true);
}

/* delete contacts */
function deleteContacts() {
    for (var i = 0, leni = gSelectedContacts.length; i < leni; i++) {
        var contactTO = getContactTOById(gSelectedContacts[i]);
        if (!contactTO) {
            closeDialog();
            return;
        }
        var addresses = [];
        if (contactTO.addresses.mobile) addresses.push(contactTO.addresses.mobile);
        if (contactTO.addresses.email) addresses.push(contactTO.addresses.email);
        var contact = new Contact(contactTO.contactUserId, contactTO.nickname, addresses);
        CM.sendRequest("contactUpdateRequest$delete", contact, "DELETE_OBJECT");
    }
}
/* callback for contactUpdateRequest$delete */
function doDeleteContacts() {
    // contacts are deleted one by one, so when reaching the last one - perform the callback.
    if (++gDeleteContactsCounter < gSelectedContacts.length) return;

    // delete contacts from gUserContactTOs and gUserCommunicationAddresses
    for (var i = 0, leni = gSelectedContacts.length; i < leni; i++) {
        removeContactFromLists(gSelectedContacts[i]);
    }
    gDeleteContactsCounter = 0;
    gSelectedContacts = [];
    closeDialog();
    createContactsList(renderContactsPane);
    $('quick_message_to').value = '';
    /* A temporary patch, ensure that if the user deleted contacts they'll be reoved from the to message */
    setFeedbackMessage('feedbackMessage', TEXT.contact_deleted, false, 5000);
}

/* remove a contact from the contact lists */
function removeContactFromLists(contactId) {
    // gUserContactTOs
    for (var i = 0, leni = gUserContactTOs.length; i < leni; i++) {
        if (contactId == gUserContactTOs[i].contactUserId) {
            gUserContactTOs.splice(i, 1);
            break;
        }
    }
    // gUserCommunicationAddresses
    for (var i = 0, leni = gUserCommunicationAddresses.length; i < leni; i++) {
        if (contactId == gUserCommunicationAddresses[i].contactUserId) {
            gUserCommunicationAddresses.splice(i, 1);
            leni = gUserCommunicationAddresses.length;	// if found a match, update the length of the array and keep iterating
        }
    }
}

/* display contact tab */
function displayContactTab(clickedEl, tabToDisplay) {
    hideElement('friendsTab', 'pendingTab', 'blockListTab');
    hideElement('emptySeperator', 'friendEmpty', 'pendingEmpty', 'blockedEmpty');
    displayElement(tabToDisplay + 'Tab');
    if (tabToDisplay == 'friends') {
        makeVisible('addFriendsButton');
    } else {
        makeHidden('addFriendsButton');
    }
    switch (tabToDisplay) {
        case 'friends':
            if (!anyContactFriends()) {
                displayElement('emptySeperator');
                displayElement('friendEmpty');
            }
            break;
        case 'pending':
            if (!anyPendingFriedns()) {
                displayElement('emptySeperator');
                displayElement('pendingEmpty');
            }
            break;
        case 'blockList':
            if (!anyBlockedFriedns()) {
                displayElement('emptySeperator');
                displayElement('blockedEmpty');
            }
            break;
    }
    //	makeHidden('feedbackMessage');
    ['friendsTabLink','pendingTabLink','blockListTabLink'].each(function(el) {
        changeStyle($(el), 'tabContact');
    });
    if (clickedEl.tagName.toLowerCase() == 'a') clickedEl = clickedEl.parentNode.parentNode;
    clickedEl.className = 'tabContactChosen';
    var filterQuickContactsField = $('filterQuickContactsField');
    if (filterQuickContactsField && filterQuickContactsField.value != '') {
        filterQuickContactsField.value = '';
        filterContacts(filterQuickContactsField);
    }
    gDisplayedContactTabContainer = tabToDisplay;
}

/* set contact blocked or unblocked */
function setContactPrivilege(action, contactId) {
    var contact = getContactTOById(contactId);
    if (contact) contact.blocked = (action != 'acceptContact');
    CM.sendRequest(action + 'PrivilegeRequest$AP', contactId, TransactionId.next());
}

function setPrivilegeRequest(action, contactId, transactionId, tab) {
    doPrivilegeRequest(action, contactId, transactionId);
    renderContactsPane(tab);
    var msg;
    var isGreen;
    if (action == 'acceptContact') {
        msg = TEXT.friend_added;
        isGreen = true;
    } else {
        msg = TEXT.friend_blocked;
        isGreen = false;
    }
    setFeedbackMessage('feedbackMessage', msg, isGreen, 3000);
}

/* set contact as unblocked (from Blocked List in add/manage contacts dialog) */
function unblockContact(contactId) {
    setContactPrivilege('acceptContact', contactId);
    renderContactsPane('blockList');
    setFeedbackMessage('feedbackMessage', TEXT.friend_unblocked, true);
}

function renderContactsPane(tabToShow) {
    gSelectedContacts = [];
    gSelectedFriends = [];
    gContactsBlock = TM.loadAndParse('contacts_pane.html', null, 'contactsContainer');
    if (!tabToShow) tabToShow = gDisplayedContactTabContainer;
    displayContactTab($(tabToShow + 'TabLink'), tabToShow);
}

/* general contact buttons envelope */
function contactButton(event, method) {
    var args = $A(arguments);
    args.splice(0, 2);
    method.apply(this, args);
    if (event.preventDefault) {
        event.preventDefault();
        event.stopPropagation();
    } else {
        event.returnValue = false;
        event.cancelBubble = true;
    }
}
/* edit contcat */
function editContact(node, contactUserId) {
    var contact = getContactTOById(contactUserId);
    node = node.parentNode.parentNode.parentNode;
    openDialog('p_edit_friend.html', contact, 250, closeEditFriend, null, null, null, null, node, 20, 44);
}

/* show contacts list mini dialog from 'to' button */
function showQuickSearchFriends(state) {
    if (gIsQuickSearchFriendsShowing) {
        hideElement('quick_searchFriends');
        if (state) {
            var recipients = $F('quick_message_to');
            if (recipients[recipients.length - 1] == ',') {
                recipients = recipients.slice(0, recipients.length - 1); // Remove last comma character
            }
            recipients = recipients.split(','); // Turn into an array
            var txt = '', address, contact;

            var quickContactsList = $('searchFriendsList').getElementsByTagName('input');
            for (var j = 0, lenj = quickContactsList.length; j < lenj; j++) {
                /* Remove all contacts from the list to prevent */
                /* unchecked contacts to stay in the list		*/
                contact = getContactTOById(quickContactsList[j].value);
                address = contact.member ? contact.username : mobileToLocal(contact.addresses.mobile) || contact.addresses.email;
                var exists = recipients.indexOf(address);
                if (exists >= 0) {
                    recipients = recipients.without(address);
                }
                if (quickContactsList[j].checked) {
                    txt += address + ',';
                }
            }

            var leni = recipients.length;
            if (recipients[0] != TEXT.friend_mobile_number) {
                for (var i = 0; i < leni; i++) {
                    txt += recipients[i] + ',';
                }
            }
            txt = txt.slice(0, txt.length - 1); // Remove last comma character

            if (!txt) txt = TEXT.friend_mobile_number;
            $I('quick_message_to', txt);
            setTextAlign('quick_message_to', TEXT.friend_mobile_number);
        }
    } else {
        gSearchFriends = TM.loadAndParse('quick_searchFriends.html', null, 'quick_searchFriends');
        setListMouseEvents('searchFriendsList');
        displayElement('quick_searchFriends');
        createSlider('searchFriendsListCont', 'quickFriendsSliderTrack', 'quickFriendsSliderHandle');

        // check contacts that are already in the 'to' field
        var recipients = $F('quick_message_to');
        if (recipients != TEXT.friend_mobile_number) {
            recipients = createRecipientsFromQuery('quick_message_to');
            var quickContactsList = $('searchFriendsList').getElementsByTagName('input');
            for (var i = 0; i < recipients.length; i++) {
                for (var j = 0, lenj = quickContactsList.length; j < lenj; j++) {
                    if (quickContactsList[j].value == recipients[i].recipientId) {
                        quickContactsList[j].click();
                        quickContactsList[j].parentNode.parentNode.className = 'searchFriendsListhover';
                    }
                }
            }
        }
    }
    gIsQuickSearchFriendsShowing = !gIsQuickSearchFriendsShowing;
}

/* open Add Friends Dialog */
function openAddFriendsDialog() {
    openDialog('p_add_friend.html', null, 250, null, null, null, null, null, $('contactsContainer'), null, 39);
}

/* Test if a memeber already exists in the current userContatTOs */
function isAlreadyContactTO(contactUserId, username, nickname) {
    for (var j = 0, lenj = gUserContactTOs.length; j < lenj; j++) {
        if (gUserContactTOs[j].contactUserId == contactUserId) return (true);
        if (gUserContactTOs[j].username == username) return (true);
        if (gUserContactTOs[j].nickname == nickname) return (true);
    }
    return(false);
}

function uniqContactTOs(anArray) {
    var returnArray = [];
    var indexArray = [];

    for (var i = 0, leni = anArray.length; i < leni; i++) {
        try {
            //Ignore Facebook communication addresses) and duplicates
            if (!indexArray.exists(anArray[i].contactUserId) && anArray[i].deviceType != 'FACEBOOK') {
                indexArray.push(anArray[i].contactUserId);
                returnArray.push(anArray[i]);
            }
        } catch (e) {
        }
    }

    return(returnArray);
}

/* Return true if there are any blocked friends, false otherwise */
function anyBlockedFriedns() {
    for (var i = 0, leni = gUserContactsList.length; i < leni; i++) {
        if (gUserContactsList[i].blocked) return true;
    }
    return false;
}

/* Return true if there are any pending friends, false otherwise */
function anyPendingFriedns() {
    var privileges = gNotifications.pendingContacts;
    return (privileges.length > 0);
}

/* Return true if there are any contact friends, false otherwise */
function anyContactFriends() {
    for (var i = 0, leni = gUserContactsList.length; i < leni; i++) {
        if ((gUserContactsList[i].contactUserId) && (!gUserContactsList[i].blocked)) return true;
    }
    return false;
}
//var gPort = '8888';
//var gPort = '80';
var gSecurePort = '8443';
var gRememberUserLogin = '';

/* login at end of registration */
function loginAfterRegister(){
	writeUIModeToCookie();
	var username = $('firstrun_username');
	if (username) username = username.value;
	var password = $('firstrun_rePassword');
	if (password) password = password.value;
	if (username && password){
		setLoginIFrame(true);
		login(username, password);
	} else {
		openLoginDialog(true);
	}
}
function downloadtriplayConnect(){
	hideElement('downloadTriplayConect');
	if(navigator.appName.indexOf('Microsoft')!=-1){
		displayElement('microsoftUsers');
	}else if(navigator.appName=='Netscape'){
		displayElement('netscapeUsers');
	}
	setTimeout("window.location.href = " + gRingtoneCreator, 3000);
}

/* open small dialog */
function openLoginDialog(isFirstRun){
	gRememberUserLogin = $N(gCookieManager.getCookie('TriplayUserLogin'), '');
	var html = TM.loadAndParse('p_login.html', null);
	if (html != ""){
		gDialogManager.show(html, 330, 'screen', null, true, false);
	}
	setLoginIFrame(isFirstRun);
}
/* open small popup */
function openDialogSimple(templateName, width){
	var html = TM.loadAndParse(templateName, null);
	if (html != ""){
		gDialogManager.show(html, width, 'screen', null, true, false);
	}
}
/* close login dialog */
function closeLoginDialog(){
	closeDialog();
}
function setBlackAlertDialog(param){
	if (!$('blackAlertDialog')){
		var div = document.createElement("div");
		div.id = "blackAlertDialog";
		div.className = "blackAlertDialog";
		div.innerHTML = param+'<a href="javascript:void(0)" onclick="$(\'blackAlertDialog\').style.display = \'none\'">'+TEXT.continue_1+'</a>';
		div = $('dialog2Holder').appendChild(div);
	}else{
		$('blackAlertDialog').innerHTML = param+'<a href="javascript:void(0)" onclick="$(\'blackAlertDialog\').style.display = \'none\'">'+TEXT.continue_1+'</a>';
	}
}

/* send login request */
function login(username, password, remember){
	var loginUsername, loginPassword;
	var signInForm = $('signInForm');
	var dialogSignInForm = $('dialogSignInForm');
	if (username && password){
		loginUsername = username;
		loginPassword = password;
		if (!remember) remember = '';
	} else if (dialogSignInForm){
		loginUsername = $F('dialog_login_username');
		loginPassword = $F('dialog_login_password');
		remember = $('dialog_remember').checked ? '1':'';
	} else {
		loginUsername = signInForm.login_username.value;
		loginPassword = signInForm.login_password.value;
		remember = (signInForm.remember.checked)?'1':'';
	}
	loginUsername = loginUsername.strip().stripScripts().stripTags();
	loginPassword = loginPassword.strip().stripScripts().stripTags();
	if (!loginUsername) {
		setBlackAlertDialog(TEXT.username_must_be_entered);
		$('blackAlertDialog').style.display = 'block';
		return false;
	}
	if (!loginPassword) {
		setBlackAlertDialog(TEXT.password_must_be_entered);
		$('blackAlertDialog').style.display = 'block';
		return false;
	}
	var cookieTime = (remember) ? 'year' : (gRememberUserLogin) ? -60 : false;
	if (cookieTime) gCookieManager.setCookie('TriplayUserLogin', loginUsername, cookieTime);
	
	//setLoginIFrame(loginUsername, loginPassword, remember);
	signInForm.usernameParameterName.value = loginUsername; 
	signInForm.passwordParameterName.value = loginPassword;
	signInForm.rememberMeParameterName.value = remember;
	signInForm.action = getSecureLoginUrl(false, gLang);
	signInForm.target = 'loginFrame';
	signInForm.submit();
	return false;
}

/* get secure login url */
function getSecureLoginUrl(isFirstRun, lang){
	var host = gAPP;
	host = host.replace(/:[0-9]+/, '');
	var firstRun = (isFirstRun) ? '?firstrun=1' : '';
	if (!lang) lang = 'en';
	lang = (firstRun?'&':'?') + 'lang=' + lang;
	return 'http://' + host + gBasepath + 'login' + firstRun + lang;
}

/* set login iframe */
function setLoginIFrame(isFirstRun){
	if ($('loginFrame')){
		document.body.removeChild($('loginFrame'));
	}
	var iframe = document.createElement("iframe");
	iframe.id = "loginFrame";
	iframe.name = "loginFrame";
	iframe.style.width = "1px";
	iframe.style.height = "1px";
	iframe.style.border = "0 none";
	iframe.src = getSecureLoginUrl(isFirstRun, gLang);
	iframe = document.body.appendChild(iframe);
}

/* forgot my password */
var gSavedSentMobileNumber;
function sendPassword(){
	gSavedSentMobileNumber = validateNumber($('mobileNumber').value);
	CM.sendRequest('SendForPassword$AP', gSavedSentMobileNumber);
}

/* callback for SendForPassword$AP */
function doSendPassword(status){
	closeLoginDialog();
	setTimeout("openDialogSimple('p_sms_sent.html', 400)",1000)
}

function sendPasswordAgain(){
	CM.sendRequest('SendForPassword$AP', gSavedSentMobileNumber);
}