var dragstarted = false;
var currentX=0;
var currentY=0;
var writing = false;
var zindexcount = 1;
var activeMenu;
clipboard = new Object;
clipboard.from = false;
clipboard.to = false;
clipboard.items = new Array;
var clipboardAction = 'copy';
var upload2share = false;
clipboard.fromuid = false;
preloaded = new Array;
var dragListBuilded = false;

function getById(id) {
	obj = document.getElementById(id);
	if (!obj) {
		return false;
	} else {
		return obj;
	}
}

function BrowserCheck() {
	var ua = navigator.userAgent.toLowerCase();
	this.Opera = ua.indexOf("opera")!=-1;
	this.IE = (!this.Opera && (ua.indexOf("msie")!=-1));
	this.NS = (!this.Opera && (ua.indexOf("mozilla")!=-1) && (ua.indexOf("compatible")==-1));
	if (this.Opera) {
		this.what = 'Opera';
	} else if (this.IE) {
		this.what = 'IE';
	} else if (this.NS) {
		this.what = 'NS';
	} 
}
is = new BrowserCheck();


function preloadImg(src) {
	index = preloaded.length;
	preloaded[index] = new Image();
	preloaded[index].src = src;
}
function imageReloadSrc() {
	this.src=this.src;
}

if (is.NS){
	document.captureEvents(Event.MOUSEMOVE);
}
function cancelBubble(e) {
	if(is.IE) {
		eveniment = window.event;
		e.returnValue = false;
		event.cancelBubble = true;
	} else {
		e.stopPropagation();  
	}
}

function getScrollLeft() {
	if (window.pageXOffset != null) {
		scroll_left = window.pageXOffset; 
	}
	if (document.body.scrollHeight != null) {
		scroll_left = document.body.scrollLeft;
	}
	return scroll_left;
}

function getScrollTop() {
	if (window.pageYOffset != null) {
		scroll_top =  window.pageYOffset;
	}
	if (document.body.scrollWidth != null) {
		scroll_top =  document.body.scrollTop;
	}
	return scroll_top;
}
function getX(event) {
	return event.clientX+getScrollLeft();
}
function getY(event) {
	return event.clientY+getScrollTop();
}
function getBodyH() {
	return ((is.NS)?document.body.clientHeight:document.body.offsetHeight);
}
function getBodyW() {
	return ((is.NS)?document.body.clientWidth:document.body.offsetWidth);
}

function newHiddenIframe(id) {
	el = document.createElement('IFRAME');
	el.name = id;
	el.id = id;
	el.src = 'blank.html';
	AfianHandler.iframesContainer.appendChild(el);
	return el;
}

function formatFileSize(filesize) {
	if (filesize >= 1024 && filesize < 1048576) {
		filesize = filesize/1024;
		dotpos = filesize.toString().indexOf(".");
		if (dotpos == -1) {
			dotpos = filesize.toString().length;
		}
		filesize = filesize.toString().substring(0,dotpos+2);
		filesize += " KB";
	} else if (filesize >= 1048576) {
		filesize = (filesize/1024)/1024;
		dotpos = filesize.toString().indexOf(".");
		if (dotpos == -1) {
			dotpos = filesize.toString().length;
		}
		filesize = filesize.toString().substring(0,dotpos+2);
		filesize += " MB";
	} else if (filesize > 0) {
		filesize = filesize;
		filesize += " Bytes";
	} else {
		filesize = "0 Bytes";
	}
	return filesize;
}

Array.prototype.has4ValidElms = function() {
	count = 0;
	for (var i = 0 ; i < this.length; i++) {
		if (this[i] != undefined) {
			count++;
		}
	}
	if (count > 3) {
	return true;
	} else {
	return false;
	}
};

function gluePath(pieces) {
	path = '';
	for (var i = 0 ; i < pieces.length; i++) {
	pieces[i] = addSingleSlashess(pieces[i]);
		if (path.substring(path.length-1, path.length) == '/') {
			if(pieces[i].substring(0, 1) == '/') {
					path += pieces[i].substring(1, pieces[i].length);
				} else {
					path += pieces[i];
				}
		} else {
			if (pieces[i].substring(0, 1) != '/') {
				if (pieces[i].length > 0) {
					path += '/'+pieces[i];
				} else {
					path += pieces[i];
				}
			} else {
				path += pieces[i];
			}
		}
	}
	return path;
}

function addSingleSlashess(str) {
	return str.replace("\\","").replace("\'","\\\'");
}

function insertHTMLBeforeEnd (el, sHTML) {
		if (el.insertAdjacentHTML != null) {
			el.insertAdjacentHTML("BeforeEnd", sHTML)
			return;
		}
		var r = el.ownerDocument.createRange();
		r.selectNodeContents(el);
		r.collapse(false);
		df = r.createContextualFragment(sHTML);
		el.appendChild(df);
}

function isLegalFilename(filename) {
	bad = new Array;
	bad[0] = "\\";
	bad[1] = "/";
	bad[2] = ":";
	bad[3] = "*";
	bad[4] = "?";
	bad[5] = "<";
	bad[6] = ">";
	bad[7] = "|";
	bad[7] = "\"";
	for (var i=0; i < bad.length ; i++) {
		if (filename.indexOf(bad[i]) != -1){
			return false;
		}
	}
	return true;
}

function debugLog(str){
	debugWindow.document.write(str);
	debugWindow.document.write('<br>');
}

function popup(url, name, height, width, scrollbars) {
	var popwin;
	var opts = "toolbar=no,status=yes,location=no,menubar=no,resizable=yes";
	opts += ",height=" + height + ",width=" + width + ",top="+(((screen.height/2)-height/2)-20)+",left=" + ((screen.width/2)-width/2) + ",scrollbars=" + scrollbars;
	popwin = window.open("", ''+name+'', opts);
	if (popwin) {
		popwin.location.replace(url);
		popwin.focus();
	}
	return popwin;
}

selectableTags=["input", "textarea", "select"];
function disableselect(e){
	if (is.IE) {
		target = event.srcElement;
	} else {
		target = e.target;
	}
		if (target.getAttribute('selectable')) {
		return true;
		} else {
			if (inArray(selectableTags, target.tagName.toLowerCase())) {
				return true;
			} else {
				return false;
			}
		}
}

function inArray(arr, needle) {
	for (var i = 0 ; i < arr.length; i++) {
		if (arr[i] == needle) {
			return true;
		}
	}
	return false;
}

if (window.name == 'AfianMainWindow') {
if (typeof document.onselectstart!="undefined") {
	document.onselectstart=disableselect;
}else{
	document.onmousedown=disableselect;
	document.onmouseup=function() {return true;};
}
}

/* COOKIES */
function setCookie(key, value) {
	document.cookie = key + "=" + escape(value);
}
function getCookie(key) {
	if (document.cookie) {
		var start = document.cookie.indexOf(' ' + key + '=');
		if (start == -1) {
			return null;
		}
		var end = document.cookie.indexOf(";", start);
		if (end == -1) {
			end = document.cookie.length;
		}
		end -= start;
		var cookie = document.cookie.substr(start,end);
		return unescape(cookie.substr(cookie.indexOf('=') + 1, cookie.length - cookie.indexOf('=') + 1));
	} else {
		return null;
	}
}
/* END COOKIES */


function insertJavaApplet(placeHolder, postURL) {
	app = document.createElement('APPLET');
	placeHolder.appendChild(app);
	app.setAttribute('archive', 'jupload.jar');
	app.setAttribute('code', 'wjhk.jupload.JUploadApplet.class');
	app.setAttribute('height', '200');
	app.setAttribute('width', '200');
	app.setAttribute('mayscript', '1');
	
	
	par = document.createElement('PARAM');
	par.setAttribute('name', 'postURL');
	par.setAttribute('value', postURL);
	app.appendChild(par);
	
	par = document.createElement('PARAM');
	par.setAttribute('name', 'text_labels[drag]');
	par.setAttribute('value', jlabels[0]);
	app.appendChild(par);
	
	
	par = document.createElement('PARAM');
	par.setAttribute('name', 'text_labels[uploading]');
	par.setAttribute('value', jlabels[1]);
	app.appendChild(par);
	
	par = document.createElement('PARAM');
	par.setAttribute('name', 'text_labels[of]');
	par.setAttribute('value', jlabels[2]);
	app.appendChild(par);
	
	par = document.createElement('PARAM');
	par.setAttribute('name', 'text_labels[files]');
	par.setAttribute('value', jlabels[3]);
	app.appendChild(par);
}

/* JAVA Upload */
var filearr = new Array();  
var JAVAUploadSettings = new Array();

function onJavaUploadBeforeUpload(){
	b = '';
	for (var i = 0 ; i < filearr.length ; i++) {
		b += filearr[i]['filename']+'\r\n';
	}
	//alert(b);
}

function onJavaUploadStart(){
	JAVAUploadSettings['tb'] = AfianHandler.allTabs[JAVAUploadSettings['tabId']];
	JAVAUploadSettings['tb'].showHourGlass();
	getById('cancelButton').style.display = 'block';
}

function onJavaUploadFinish(){
	JAVAUploadSettings['tb'].hideHourGlass();
	cd(JAVAUploadSettings['tb'].basepath, false, JAVAUploadSettings['tb'].title);
	getById('cancelButton').style.display = 'none';
}

function cancelJavaUpload() {
	document.applets[0].stopUpload();
	document.applets[0].reset();
	getById('cancelButton').style.display = 'none';
	JAVAUploadSettings['tb'].hideHourGlass();
	cd(JAVAUploadSettings['tb'].basepath, false, JAVAUploadSettings['tb'].title);
	var div = getById('juploadHTMLCode');
	var html = getById('juploadHTMLCodeTextarea').value;
	div.innerHTML = html;
}

function onJavaUploadReply(replytext){
	console.log(replytext);
	boundarStart = '---REPLY START---';
	var boundaryStartPos = replytext.indexOf(boundarStart);
	pos = boundaryStartPos+boundarStart.length;
	var withoutHeader = replytext.substring(pos);
	var reply = withoutHeader.substring(0, withoutHeader.length-15);
	replyParts = reply.split("|");
	replyAction = replyParts[0];
	replyMsg = replyParts[1];
	if (replyAction == 'CANCEL') {
		cancelJavaUpload();
	}
	if (replyMsg != undefined) {
		AfianAlert(replyMsg);
	}
}

function addFile(filename, fullpath, filesize, uploaded) {
	var nFile = new Array();
	nFile['filename'] = filename;
	nFile['fullpath'] = fullpath;
	nFile['filesize'] = filesize;
	nFile['uploaded'] = uploaded;
	filearr.push(nFile);
}

function clearFiles() {
	fileArr = new Array();
}
