/*
/****************
/ radar section
/****************
*/
function UploaderRadar (params) {
	//{'t': 'radar_type', 'p': 'project', 'f': 'frontend'}
	if (!params) params = {};
	this.radar_type = params.t ? params.t : "common";
	this.radar_proj = params.p ? params.p : "filez";
	this.render_time = params.render_time ? params.render_time : 0;
	this.enabled = (typeof params.enabled != "undefined")  ? params.enabled : true;

    this.rT = {};
	this.rT.i = [];

	this.timeInterval  = function(bP) {
		if (!this.rT[bP]) this.rT[bP] = new Date();
		else {
			jswarn_l(7, "RadarSet:" + bP);
			this.rT.i[this.rT.i.length] = bP + '=' + ( (new Date()).getTime() - this.rT[bP].getTime() );
			delete this.rT[bP];
			jswarn_l(7, "RadarSet2:" + bP);
		}
	}

	this.timeEvent  = function(bP, delta) {
		jswarn_l(7, "RadarEvent1:" + bP);
		this.rT.i[this.rT.i.length] = bP + '=' + delta;
		jswarn_l(7, "RadarEvent2:" + bP);
	}

	this.fmt = function(a) { return Math.floor(a*1000)/1000; }
	this.rnd = function () {return Math.ceil(Math.random() * 999999999);}

	this.sendData = function() {
        if (this.rT.i.length == 0) {return};
		var iGet = '';
		var comma = "";

		for (var i = 0; i < this.rT.i.length; i++) {
			comma = iGet != '' ? ',' : '';
			var bP = this.rT.i[i].split('=');
			iGet += (comma + bP[0] + ':' + bP[1]);
		}

		this.imgrc  = 'http://filez.radar.imgsmail.ru/update?p=' + this.radar_proj + '&t=' + this.radar_type +'&v=' + this.fmt(this.render_time);
		this.imgrc += '&i=' + iGet + '&rnd='+ this.rnd() + (document.referrer ? '&r=' + escape(document.referrer) : '');
		if (this.enabled) {
			this.img = new Image();
			this.img.src = this.imgrc;
		}
		this.rT.i = [];
		jswarn_l(7, "Radar^: " + iGet);
	}
}

window.FilesRadar = new UploaderRadar();

/*
/****************
/ binder section
/****************
*/

try {
	gJsReady({'name': 'radar'});
} catch (e) {};

function init_uploader (params, compatibilityMode) {
	if (!params) params =
		{'ServerName': 'files.mail.ru'
		,'LoggedIn': false
		,'MaxFileSize': 100*1024*1024
		,'SpaceLeft': 1*1024*1024*1024
		};
	if (!params.baseURL) params.baseURL = "/";
	var allowFlashUploader = false;
	var urlCompMode = window.location.toString().match(/mode=(\w)/i);
	if (urlCompMode !== null) { urlCompMode = compatibilityMode = true; }
	//if (window.location.toString().match(/fakebutton|mode=1b/i)) params.fakeJsButton = true;
	params.fakeJsButton = true;

	var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
	var isLinux = (navigator.platform.indexOf("Linux") != -1) ? true : false;
	if (window.swfobject && typeof compatibilityMode == "undefined") {
		if ((isWin && swfobject.hasFlashPlayerVersion("9.0.28")) ||
			(false && isLinux && swfobject.hasFlashPlayerVersion("10.0.22"))) {
			allowFlashUploader = true;
		}
		if (window.location.toString().match(/skipbrowsercheck|forceflash/i)) allowFlashUploader = true;
	}

	if (allowFlashUploader) {
		MRUUploader = new FilesFlashUploader();
		MRUUploader.stamp = "F-" + GetRandomID();
	} else {
		MRUUploader = new FilesIFrameUploader();
		MRUUploader.stamp = "I-" + GetRandomID();
		if (window.AjaxFlash) AjaxFlash.WaitForFlashTicks = 0;
	}

	if (MRUUploader) {
		document.getElementById('contextUploaderMainContainer').style.display="block";
		MRUUploader.init(
			{'isLoggedIn': params.LoggedIn
			,'objHost': params.ServerName
			,'objURL': "/uploader9.swf?v=13&f=1"
			,'browseText': t('BrowseText')
			,'startBehavior': 2
			,'uploadObjContainer': 'uploadObjContainer'
			,'wmode': typeof params.wmode != "undefined" ? params.wmode : "true"
			,'objWidth': (window.gLanguageCode == 'EN') ? "77" : "120"
			,'objHeight': params.objHeight ? params.objHeight : "22"
			,'Lang': ((window.gLanguageCode) ? window.gLanguageCode : "RU")
			,'SourceHost': params.SourceHost

			,'fakeJsButton': params.fakeJsButton ? params.fakeJsButton : true
			,'fakeJsButtonClassPrefix': params.fakeJsButtonClassPrefix ? params.fakeJsButtonClassPrefix : "FakeJsButton"
			,'useButtonGlyph': params.useButtonGlyph ? params.useButtonGlyph : true
			,'buttonGlyphURL': "/mail/ru/images/files/browse_js_glyph_" + ((window.gLanguageCode) ? window.gLanguageCode : "RU") + ".gif"

			,'cbOnExpiredSession': function () {
				var groupCode = MRUUploader.servers[MRUUploader.flzid].GroupCode;
				document.location.href =  params.baseURL + "?uploadexp=1" + (groupCode ? "&incompletecode=" + groupCode : "") + (params.LoggedIn ? "&loggedin=1" : "");
			}
			,'cbOnBackendCreate': function (isflash) {
				setTimeout(function () {
					var obj_length = document.getElementsByTagName("object").length;
					if (isflash &&  obj_length > 0) {
						var delta = AjaxFlash.WaitForFlashTicksOrg - AjaxFlash.WaitForFlashTicks;
						delta = delta >= 3000 ? delta : 3000;
						AjaxFlash.WaitForFlashTicks += delta;
						if (!MRUUploader.Initialized) {
							jswarn_l(1, "cbOnBackendCreate, give-a-chance!=+" + delta);
							if (document.getElementById('listAjaxIndicator')) { document.getElementById('listAjaxIndicator').style.display = "block";}
							if (document.getElementById('listAjaxIndicator')) { document.getElementById('listAjaxIndicator').style.visibility = "visible";}
						} else {
							jswarn_l(1, "cbOnBackendCreate, too late to give a chance :(");
						}
					} else if (obj_length == 0) {
						AjaxFlash.WaitForFlashTicks = 0;
						jswarn_l(0, "cbOnBackendCreate, NoBackend!?=" + isflash);
					}
				}, 400);
			}
			});

		if (allowFlashUploader) {
			AjaxFlash.SetAjaxReadyCallback(function (flashIsOk, versionString) {
				var vstr = flashIsOk + '/' + versionString + " /cmp=" + (typeof compatibilityMode != "undefined" ? "yes" : "no");
				if (flashIsOk) {
					jswarn_l(2,"Sync.Init1/FlashOK:" + vstr);
					init_uploader_final(params);
				} else {
					jswarn_l(2,"Sync.Init1/FlashIssue:" + vstr);
					if (!compatibilityMode) {
						MRUUploader = {};
						setTimeout(function () {init_uploader(params, true)}, 200);
					}
				}
			});
		} else {
			if (typeof compatibilityMode != "undefined") {
                jswarn_l(2,"Compatible.Init/JS:" + (typeof compatibilityMode != "undefined" ? "yes" : "no"));
			} else {
				jswarn_l(2,"Instant.init/JS:" + (typeof compatibilityMode != "undefined" ? "yes" : "no"));
			}
			init_uploader_final(params);
		}
	}
	jswarn("init_uploader fin");
}

function init_uploader_final (params) {
		jswarn("init_uploader_final");
		UIobj = new FilesSplashUI('listContainer', 
			{'numeric': true
			,'linkPrefix': 'http://' + params.ServerName + '/'
			,'clearContainer': params.clearContainer
			});

		MRUUploader.onFileChoose = function(id,name,size, serObj, itemsArr) {return UIobj.onAdd(id,name,size, serObj, itemsArr);};
		MRUUploader.onUploadReady = function (id) {return UIobj.onReady(id);}
		MRUUploader.onUploadStart = function (id) {return UIobj.onStart(id);}
		MRUUploader.onBeforeUpload = function (id) {return UIobj.onApproveUppload(id);}
		MRUUploader.onUploadStop = function (id) {return UIobj.onStop(id);}
		MRUUploader.onUploadRetry = function (id) {return UIobj.onRetry(id);}

		MRUUploader.onUploadCompleted = function (id, dataObj, extraData) {UIobj.onDone(id, dataObj, extraData); return true;}
		MRUUploader.onUploadProgress = function (id, bytesLoaded, bytesTotal) {UIobj.onProgress(id, bytesLoaded, bytesTotal); return true;}
		MRUUploader.onUploadError = function (id, errorNumber, isCustom) {UIobj.onUploadError(id, errorNumber, isCustom); return true;}
		MRUUploader.onBeforeUploadTerminate = function (id, dataObj) {return UIobj.onBeforeUploadTerminate(id, dataObj);};
		MRUUploader.onStatisticsChange = function (serverObj) {return UIobj.UpdateUploadStatistics(serverObj);};
		MRUUploader.cbOnInitComplete = function (initializedWellNow, initializedNow) {
			if (document.getElementById('listAjaxIndicator')) { document.getElementById('listAjaxIndicator').style.display = "none";}
			if (initializedWellNow == initializedNow) {
				jswarn_l(2,"cbOnInitComplete = ALL OK");
			} else {
				jswarn_l(2,"NoJs Mode shoud be turned ON :(");
			}
		}
		MRUUploader.onStatisticsChange = function (data) {UIobj.UpdateUploadStatistics(data)}

		MRUUploader.onUploadIssueNotification = function (data, issueArr) {
			if (typeof gErr == "undefined") return true;
			var UpServerId = issueArr.length > 0 ? issueArr[issueArr.length - 1].id : null;
			var errorRepObj = new Hash();
			for (var i=0; i< issueArr.length; i++) {
				for (var j=0; j< issueArr[i].errors.length; j++) {
					var err = issueArr[i].errors[j];
					if (err == gErr.ISEMPTY) errorRepObj.setItem(gErr.ISEMPTY, true);
					if (err == gErr.TOOMANY) errorRepObj.setItem(gErr.TOOMANY, true);
					if (err == gErr.DENIED) errorRepObj.setItem(gErr.DENIED, true);
					if (err == gErr.NOSPACE) errorRepObj.setItem(gErr.NOSPACE, true);
					if (err == gErr.TOOBIG) errorRepObj.setItem(gErr.TOOBIG, true);
				}
			}
			var message = null;
			if (errorRepObj.hasItem(gErr.TOOMANY)) {
				message = ts('TooManyFilesToUpload', MRUUploader.queue.ListLimit);
			} else if (errorRepObj.hasItem(gErr.TOOBIG)) {
				message = ts('TooBigFileDetailed1', data.fileName, params.MaxFileSize) + t('TooBigFileDetailed2R');
			} else if (errorRepObj.hasItem(gErr.NOSPACE)) {
                if (MRUUploader.queue.queueIsActive) {
					message = ts('NoSpaceToUploadCalc',data.fileName, MRUUploader.servers[UpServerId].SrvSpaceLeftCalc, data.fileSize);
				} else {
                    message = ts('NoSpaceToUpload',data.fileName, MRUUploader.servers[UpServerId].SrvSpaceLeft, data.fileSize);
				}
			} else if (errorRepObj.hasItem(gErr.ISEMPTY)) {
				message = ts('NullSizeFile', data.fileName);
			}
			if (message) alert(message);
		}

		UIobj.cbRetry = function (id) {return MRUUploader.RetryUpload(id);}
		UIobj.cbTerminate = function (id) {return MRUUploader.TerminateUpload(id);}
		UIobj.cbGetFileServer = function (id) {return MRUUploader.GetFileServer(id)};

		MRUUploader.queue.ListLimit = 20;
		MRUUploader.queue.onQueueChanged = function (length, itemsIds) {
			if (params.GroupButton) {
				if (document.getElementById(params.GroupButton))
					document.getElementById(params.GroupButton).disabled = (MRUUploader.queue.CalcLength() != 0) ? false : true;
			}
			UIobj.onRenumber(itemsIds)
		}

		var UploadSpeedMeter;
		if (typeof SpeedMeter != "undefined") {
			UploadSpeedMeter = new SpeedMeter({'baseObjId': 'pnlSpeedMeters'});
			MRUUploader.cbSpeedMeterTick = function(obj) {UploadSpeedMeter.ProcessSpeedSmaple(obj)};
			MRUUploader.queue.onQueueBeforeFinish = function () {
				UploadSpeedMeter.ResetMeter();
				if(window.gIsNewbie) try{ document.getElementById('pnlNewbieHelp').style.display = 'none'; window.gIsNewbie = false;} catch (e) {};
				};
		}
		//delayed submit?!
		//MRUUploader.queue.onQueueStart = function () { MRUUploader.queue.onQueueFinish = function () {}};
		
		var locGroupCode = window.location.toString().match(/incompletecode=(\w+)&/i);
		if (locGroupCode !== null) {
			locGroupCode = locGroupCode[1];
		}

		var UpServerFiles = new FilesUpServer();
		UpServerFiles.Init(
			{'uid': 'Filez'
			,'UpHost': 'http://' + params.ServerName
			,'AjaxHost': 'http://' + params.ServerName
			,'MaxFileSize': params.MaxFileSize
			,'SpaceLeft': params.SpaceLeft
			,'SrvListLimit': 20
			,'GroupCode' : locGroupCode
			,'ServerPriority' : 1
			//,'AutoRestore': true
			,'DontCheckSpace': params.DontCheckSpace
			,'UpMode': params.UpMode
			});
		UpServerFiles.cbOnGroupCodeChange = function (linkcode) {return UIobj.onLinkUpdate(linkcode);};
		UpServerFiles.cbOnFolderStatistics = function (dataArr) {
			var usedSizeMB = dataArr.shift()/1024/1024;
			var totalCount = dataArr.shift();
			if (usedSizeMB == 0 && totalCount == 0) {return};
			if (typeof $('fcount_label') != "undefined") {
				var new_progress = 0;
				if(usedSizeMB > 0 && usedSizeMB < 1) {
					new_progress = 1;
				} else {
					new_progress = Math.floor(usedSizeMB);
				}
				$('fmeter_label').firstChild.nodeValue =  new_progress + t('UnitsMB');
				$('fcount_label').firstChild.nodeValue =  totalCount;
			}

			if (typeof $('ffoldercnt1') != "undefined") {
				if (dataArr.length % 3 == 0) {
					for (j=0; j < (dataArr.length)/3; j++) {
						var FolderId = dataArr[j*3];
						$('ffoldercnt' + FolderId).firstChild.nodeValue = dataArr[j*3 + 1];
					}
				}
			}
		}
		if (params.ForceLimit) {
            UpServerFiles.DontTakeNewStat = true;
		}

		MRUUploader.flzid = MRUUploader.AddUploadServer(UpServerFiles);
		if (params.FilesIn) {
			MRUUploader.RestoreServerData( MRUUploader.flzid,
					                {	'stat': {'SpaceLeft': params.SpaceLeft },
				                    	'list': params.FilesIn
				                    });
		} else {
			MRUUploader.InitializeUploadServer(MRUUploader.flzid);
		}

		AjaxFlash.cbOnExpiredSession = function (URL, PostID) {
			var groupCode = MRUUploader.servers[MRUUploader.flzid].GroupCode;
			document.location.href = params.baseURL + "?ajaxexp=1" + (groupCode ? "&incompletecode=" + groupCode : "") + (params.LoggedIn ? "&loggedin=1" : "");
		};
}

try {
	gJsReady({'name': 'binder'});
} catch (e) {};