/* BREAK FRAMES */
if (top.location !== self.location) {
	self.location = "http://kodingen.com/w/";
}

if (typeof Object.create !== "function") {
	Object.create = function(o) {
		var F = function() {};
		F.prototype = o;
		return new F();
	};
}
var __k = {};

__k.base = { 
	_author	: "Sinan Yasar, Lead UI, Kodingen - 19.01.2010",
	_version : "0.3",
	_ready : true,
	get_version : function(){
		var that = this;
		$.post(__k.base.ajaxUrl.version_checker, {}, function(d){
			if(that._version !== d.k){
				__k.utils.loading('A new version of Kodingen is available. To update, please <a target="_blank" href="http://www.wikihow.com/Clear-Your-Browser\'s-Cache">clean your browser cache</a> and refresh.',1,true);
			}
		},"json");
	},
	ajaxUrl : {
		save 		: "k.php",
		def 		: "k.php",
		cm_path		: "/kodingen/quickMenu/contextMenu/",
		logout 		: "/w/wp-login.php",
		taskListener: "k_listener.php",
		version_checker : "/_gui_ver.json"
	},
	quickMenu : {
		uploader		: "/kodingen/quickMenu/uploader_json.php",
		ftp_list_json	: "/kodingen/quickMenu/ftp_list_json.php",
		application_selector : "/kodingen/quickMenu/application_selector_json.php"
	},
	editors : {
		pixlr_editor	: "http://www.pixlr.com/editor/",
		pixlr_express	: "http://www.pixlr.com/express/",
		jaycut			: "http://mixerbeta.jaycut.se/accounts/temporary"		
	},
	browserDetect : {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
						return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser: [
			{
				string: navigator.userAgent,
				subString: "Chrome",
				identity: "Chrome"
			},
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				identity: "Safari",
				versionSearch: "Version"
			},
			{
				prop: window.opera,
				identity: "Opera"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				   string: navigator.userAgent,
				   subString: "iPhone",
				   identity: "iPhone/iPod"
		    },
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}
		]
	
	}
};
/* !K APP DEFAULTS */
__k.app_defaults = {
	extension_sets : {
		code_files 	: ["php", "pl", "py", "jsp", "asp", "htm","html", "phtml","shtml", "sh", "cgi", "htaccess","fcgi","wsgi","mvc","xml","sql","rhtml","js","json","css", "txt", "doc", "rtf", "csv"],
		image_files : ["png","gif","jpg","jpeg","bmp","svg"],
		video_files : ["avi","mp4","h264","mov","mpg"]
	}
};

/* !K UTILS */
__k.utils = {
	task_memo : {},
	taskListener : function(taskId, cmd, callback) {
		var interval = 500,
			listenerUrl = "/task.php",
			counter = 0,
			max_attempts = 5;
		
		function postTask(taskId, callback) {
			if(counter < max_attempts){
				$.getJSON(listenerUrl, { "t" : taskId }, function(response,a) {
					if (response.status !== "5"){
						if(response.status === "-2"){
							$(__ft1.options._holder).unblock();
							$(__ft1.options._holder).block({ message: '<p class="filetree_loader"></p><br/><p class="red">Creating file structure<br/>please wait</p>' });
							var t = setTimeout(function() {
								$(__ft1.options._holder).unblock();
								__ft1.init_tree();
							},5000);
						}else{
							var t = setTimeout(function() {
								postTask(taskId, callback);
							},interval);
							interval = (interval > 10000 ) ? 10000 : interval*1.5;
						}
						__k.utils.taskLogger.print(taskId,response.response + "<br/>");
					}else{
						if ($.isArray(response.response)){
							$.each(response.response, function(i,t) {
								__k.utils.taskLogger.print(taskId,t + "<br/>");
							});
						}else{
							__k.utils.taskLogger.print(taskId,response.response + "<br/>");
						}
						__k.utils.task_memo[taskId]["output"] = response;
						
						callback.call(null,response);
						
					}
				});
			}else{
				var $log = $("<span>Operation is still in queue, to check its status </span>");
					$log_action = $("<span class='log_action'>please click here.</span>");
				
				$log.append($log_action);
				__k.utils.loading("Kodingen servers are busy. Please <span class='loading_close green' onclick='__k.layout.section.bottom.open()'>click here</span> to see details. <span class='loading_close green'>[close]</span>",5000,true);
				__k.utils.taskLogger.print(taskId,$log);
				
				//bind event to log action
				$log_action.one('click', function() {
					counter = 0;
					$log.after("Checking operation status...<br/>").remove();
					postTask(taskId, callback);
				});
				return false;
			}
			counter++;
		}

		postTask(taskId, callback);
		__k.utils.taskLogger.print(taskId, cmd + "<br/>");
	},
	taskLogger : {
		logHolder 	: "#task_logger",
		scroll		: function(reset) {
			var st = (reset) ? 0 : 500000;
			$(this.logHolder).scrollTop(st);
		},
		print		: function(taskId, log, complete) {
			if ( $(this.logHolder).find('li#task_log_'+taskId).length !== 0 ) {
			
				$(this.logHolder).find('li#task_log_'+taskId).append(log);
			
			}else{
				var $li = $('<li id="task_log_'+taskId+'"></li>');
				$li.append(log);
				$(this.logHolder).append($li);
			
			}
			
			this.scroll();
			
			var that = this;
			if (complete || $(this.logHolder).find('li').length > 50){
				var t = setTimeout(function() {
					that.clear();
				},5000);
			}
		},
		clear		: function() {
			var that = this;
			$(that.logHolder).find('li').fadeOut(200, function() {
				$(this).remove();
				that.scroll(true);
			});	
		}
	},
	modalMessage : function(title, message, overlay){
		overlay = overlay || true;
		
		//--SET MODAL TITLE
		$("h6.modal_generic").html(title);
		$("div#parent_modal_message_content").html(message);
			 
	    $("#container_editor").block({
	    	message: $("#parent_modal_message"),
	    	showOverlay:  overlay,
	    	cursor: 'default',
	    	overlayCSS : {
	    		backgroundColor : "#000"
	    	}
	    });		
	},
	modalMessageUI : function(message, options){
		//message[HTML]
		//options[object] - jquery ui default
		var $dialog = $("div#kodingen_modal_box");
		
		$dialog.html(message);
		
		$dialog.dialog(options).show(400);
		
		$dialog.bind('dialogclose', function() {
		  $dialog.dialog('destroy');
		});		
	},
	httpwebserver : {
		onload : function(frame_id) {
			var $frame = $("#kd_tabs #"+frame_id),
				url = $frame.contents().location;
			$frame.parent().find("input[name=kd_http_address_bar]").val(url);
		}
	},
	console : function(a) {
		if (typeof window.console !== "undefined" ){
			console.log(a);		
		}
	},
	save_code_content : function(file_path, content) {
		var params = { 
				"file_path"	: file_path, 
				"content"	: content, 
				"operation" : "save_editarea_content"
			};
		$.post(__k.base.ajaxUrl.save, params, function(r,s){
				if (typeof r === "object" && typeof r.taskId !== "undefined"){
					__k.utils.task_memo[r.taskId] = {};
					__k.utils.task_memo[r.taskId]["input"] = params;
					__k.utils.task_memo[r.taskId]["command"] = r;
				}
				__k.utils.taskListener(r.taskId, r.cmd, function(d) {
					if(d !== null || typeof d === "object" && d.status === "5") { 
						$.growlUI('File :' + file_path, 'File is saved!','growl_ok');	
					}else{
						__k.utils.loading("There was a problem while saving your file, please try again later! <span class='log_action'>[close]</span>","",true);
					}
					return delete __k.utils.task_memo[d.taskId];
				});
			}, "json"); 
	},
	startTime	: function() {
		var d = new Date();
		this._time = d.getTime();
	},

    getTimeDiff	: function (){
        d = new Date();
        var a = this._time;
        __k.utils.startTime();
        return (d.getTime()-a + "ms.");
    },

    _time : 0,
    postback_map : {
    	_findPath : function(taskId) {
    		var refresh_path = "/";
    		$.each(__k.utils.task_memo[taskId].input, function(k,v) {
				if (typeof v === "object"){
	    			if (v.name === "path" ){
	    				refresh_path = v.value;	
	    			}
	    		}else{
	    			if (k === "path" ){
	    				refresh_path = v;	
	    			}
	    		}
    		});
			return refresh_path; 
    	},
    	_clearTask : function(taskId) {
			if(__k.quickMenu._isLocked){
				delete __k.utils.task_memo[taskId];
			}else{
				__k.quickMenu.slideRight(function() {
					delete __k.utils.task_memo[taskId];
				});
			}
    	},
    	"new_file" : function(r,taskId) {
    		var refresh_path = __k.utils.postback_map._findPath(taskId);
			window.__ft1.init_tree.call(__ft1, refresh_path);
			__k.utils.postback_map._clearTask(taskId);
			
    	},
    	"new_folder" : function(r,taskId) {
    		var refresh_path = __k.utils.postback_map._findPath(taskId);
			window.__ft1.init_tree.call(__ft1, refresh_path);
			__k.utils.postback_map._clearTask(taskId);
    	},
    	"rename" : function(r,taskId) {
    		var refresh_path = __k.utils.postback_map._findPath(taskId);
			window.__ft1.init_tree.call(__ft1, __k.utils.returnParentPath(refresh_path));
			__k.utils.postback_map._clearTask(taskId);
    	},
    	"delete" : function(r,taskId) {
    		var refresh_path = __k.utils.postback_map._findPath(taskId);
			window.__ft1.init_tree.call(__ft1, __k.utils.returnParentPath(refresh_path));
			__k.utils.postback_map._clearTask(taskId);
    	},
    	"chmod" : function(r,taskId) {
    		var refresh_path = __k.utils.postback_map._findPath(taskId);
			window.__ft1.init_tree.call(__ft1, __k.utils.returnParentPath(refresh_path));
			__k.utils.postback_map._clearTask(taskId);
    	},
    	"compress" : function(r,taskId) {
    		var refresh_path = __k.utils.postback_map._findPath(taskId);
			window.__ft1.init_tree.call(__ft1, __k.utils.returnParentPath(refresh_path));
			__k.utils.postback_map._clearTask(taskId);
    	},
    	"download" : function(r,taskId) {
    		var refresh_path = __k.utils.postback_map._findPath(taskId);
			window.__ft1.init_tree.call(__ft1, __k.utils.returnParentPath(refresh_path));
			__k.utils.postback_map._clearTask(taskId);
    	},
    	"extract" : function(r,taskId) {
    		var refresh_path = __k.utils.postback_map._findPath(taskId);
			window.__ft1.init_tree.call(__ft1, __k.utils.returnParentPath(refresh_path));
			__k.utils.postback_map._clearTask(taskId);
    	},
    	"copy_files" : function(r,taskId) {
    		var refresh_path = "/";
    		$.each(__k.utils.task_memo[taskId].input, function(k,v) {
    			if (v.name === "target_path"){
    				refresh_path = v.value;	
    			}
    		});
			window.__ft1.init_tree.call(__ft1, __k.utils.returnParentPath(refresh_path));
			__k.utils.postback_map._clearTask(taskId);
			$(__ft1.options._tree).unblock();
    	},
    	"move_files" : function(r,taskId) {
    		var refresh_path = "/";
    		$.each(__k.utils.task_memo[taskId].input, function(k,v) {
    			if (v.name === "target_path"){
    				refresh_path = v.value;	
    			}
    		});
			window.__ft1.init_tree.call(__ft1, __k.utils.returnParentPath(refresh_path));
			__k.utils.postback_map._clearTask(taskId);
			$(__ft1.options._tree).unblock();
    	},
    	"zip_download" : function(r,taskId) {
    		var refresh_path = __k.utils.postback_map._findPath(taskId);
			window.__ft1.init_tree.call(__ft1, __k.utils.returnParentPath(refresh_path));
			__k.utils.postback_map._clearTask(taskId);
    	},
    	"publish_path_to_url" : function(r,taskId) {
			var o = {};
			o.download_path = __k.utils.task_memo[taskId].output.response[1];
			o.path = __k.utils.task_memo[taskId].input.path;
			__k.quickMenu.loadData(__k.base.ajaxUrl.cm_path + "download.php", o);
			__k.utils.postback_map._clearTask(taskId);
    	},
    	"add_app" : function(r,taskId) {
    		var refresh_path = "/";
			window.__ft1.init_tree.call(__ft1, refresh_path);
			//__k.utils.loading("Application is installed.", 5000,true);
			__k.utils.postback_map._clearTask(taskId);
    	},
    	"add_ftp" : function(r,taskId) {
			__k.quickMenu.loadData(__k.base.quickMenu.ftp_list_json);
			__k.utils.postback_map._clearTask(taskId);
    	},
    	"remove_ftp" : function(r,taskId) {
			__k.quickMenu.loadData(__k.base.quickMenu.ftp_list_json);
			__k.utils.postback_map._clearTask(taskId);
    	}
    },
    save_prefs	: function(url, params, callback) {
    	url = url || __k.base.ajaxUrl.save;

		$.post(url, params, function(r,s) {
			if (typeof r === "object" && typeof r.taskId !== "undefined"){

				__k.utils.task_memo[r.taskId] = {};
				__k.utils.task_memo[r.taskId]["input"] = params;
				__k.utils.task_memo[r.taskId]["command"] = r;

				__k.utils.taskListener(r.taskId, r.cmd, function(response) {
					$.each(params,function(k,v) {
						if (typeof v === "object"){
							if (v.name === "operation" && typeof __k.utils.postback_map[v.value] !== "undefined"){
								__k.utils.postback_map[v.value].call(null,response,r.taskId);
							}
						}else{
							if (k === "operation" && typeof __k.utils.postback_map[v] !== "undefined"){
								__k.utils.postback_map[v].call(null,response,r.taskId);
							}
						}
					});
				});

			}
			
			if(typeof r.postback === "object"){
				switch (r.postback.type) {
					case "menu" :

						__k.quickMenu.loadData(r.postback.url, r.postback.params);

					break;
					case "reloadFileTree" :

						window.__ft1.init_tree.call(__ft1, r.postback.params.path);
						$(window.__ft1.options._tree).unblock();
						__k.quickMenu.slideRight();
					
					break;
					case "error_message" :
						if (typeof r.postback.close !== "undefined" && r.postback.close === "click"){
							__k.utils.loading(r.postback.message, 5000, true);
						}else{
							__k.utils.loading(r.postback.message, 5000);
						}
					break;
				}
			}
			
			if(typeof callback !== "undefined"){
				callback.call(null,r,s);
			}
		},"json");    	
    },
    closeModalAndCancel : function(){
		$.unblockUI();
		$("#container_editor").unblock();
		$("#kodingen_modal_box").html("").hide();
	}, 
    success_msg : function(a) {
    	alert(a);
    },
	open_in_tab : function(title) {
		__k.utils.sendFileToEditor.call(window,__k.user.data.user_login+'.phpmyadmin', title);
	},
    loading 	: function(msg,dur,self_close) {
		var $msg = $("#kd_loading");
		if(typeof msg !== "undefined" && typeof dur === "undefined" && typeof self_close === "undefined"){
			$msg.html(msg);
			var w = $msg.outerWidth();
			var r = ( __k.layout.winWidth - w )/2;
			$msg.css("right",r);
			$msg.fadeIn(200);
		}else if(typeof msg !== "undefined" && typeof dur === "number" && typeof self_close === "undefined"){
			var $mmsg = $("<div class='h10'></div>");
			$mmsg.html(msg);
			$mmsg.appendTo('body');
			var w = $mmsg.outerWidth();
			var r = ( __k.layout.winWidth - w )/2;
			$mmsg.css("right",r);
			
			var t = setTimeout(function() {
				$mmsg.fadeOut(400, function() {
					$mmsg.remove();	
				});
			},dur);	
			$mmsg.click(function() {
				$mmsg.fadeOut(400, function() {
					$mmsg.remove();	
				});
			});
		}else if(typeof msg !== "undefined" && self_close === true){
			var $mmsg = $("<div class='h10'></div>");
			$mmsg.html(msg);
			$mmsg.appendTo('body');
			var w = $mmsg.outerWidth();
			var r = ( __k.layout.winWidth - w )/2;
			//__k.utils.console([w,r,__k.layout.winWidth]);
			$mmsg.css("right",r);
			var tt = setTimeout(function() {
				$mmsg.fadeOut(400, function() {
					$mmsg.remove();	
				});
			},30000);

			$mmsg.click(function() {
				$mmsg.fadeOut(400, function() {
					clearTimeout(tt);
					$mmsg.remove();
				});
			});
			
		}else{
			$msg.fadeOut(400);
		}
    },
    returnExtension : function(path) {
		var ext = false,
			extension = false;
		if (path.search(/\//) !== -1){
			extension = path.split("/");
			extension = extension[extension.length -1];
			if (extension.search(/\./) !== -1){
				extension = extension.split(".");
				ext = extension[extension.length -1];
			}
		}else{
			if (path.search(/\./) !== -1){
				extension = path.split(".");
				ext = extension[extension.length -1];
			}
		}
		return ext;
    },
    returnFileName : function(path) {
		var fn = false;
		if (path.search(/\//) !== -1){
			fn = path.split("/");
			fn = fn[fn.length-1];
			if (fn.search(/\./) !== -1){
				fn = fn.split(".");
				fn.pop();
				fn = fn.toString().replace(/,/gi,".");
			}
		}else{
			fn = path;
			if (path.search(/\./) !== -1){
				fn = path.split(".");
				fn.pop();
				fn = fn.toString().replace(/,/gi,".");
			}
		}
		return fn;
    },
    returnFileFullName : function(path) {
		var ffn = false;
		if (path.search(/\//) !== -1){
			ffn = path.split("/");
			ffn = ffn[ffn.length-1];
		}else{
			ffn = path;
		}
		return ffn;
    },
    returnParentPath : function(path) {
		var pp = false;
		if (path.search(/\//) !== -1){
			pp = path.split("/");
			pp.pop();
            pp = pp.toString().replace(/,/g,"\/");
			pp = (pp === "") ? "/" : pp ; 
		}else{
			pp = path;
		}
		//pp = (pp.substr(-1,1) !== "/") ? pp+"/" : pp;
		return pp.replace(/\/\//g,"\/");
    },
	isTabOpen : function(myFileNameWithPath) {
		//IF FILE IS NOT OPEN CREATE ITS TAB
		//alert($("#kd_tabs div").length+" and "+$("#kd_tabs div[for=_header_php]").length);
		if ( $("#kd_tabs div[rel="+__k.utils.createDecentSelector(myFileNameWithPath)+"]").length === 0 ){
			return false;
		//ELSE TAKE FILE'S PATH GUESS ITS ID AND TRIGGER A CLICK ON IT	
		}else{
			var tabPath = __k.utils.createDecentSelector(myFileNameWithPath);
			//IF IT IS OPEN AND FOCUSED SHAKE IT
			if($("a[rel=kd_tab_a"+tabPath+"]").parent().hasClass("ui-tabs-selected")){
				$("a[rel=kd_tab_a"+tabPath+"]").parent().effect("shake",{times: 3}, 100);
				/* WITHOUT UI EFFECTS
				$("a[rel=kd_tab_a"+tabPath+"]").parent()
					.animate({ left: -10 }, { duration: 75, easing: "easeOutQuad"})
					.animate({ left: 10 }, { duration: 75, easing: "easeOutQuad"})
					.animate({ left: -10 }, { duration: 75, easing: "easeOutQuad"})
					.animate({ left: 10 }, { duration: 75, easing: "easeOutQuad"})
					.animate({ left: 0 }, { duration: 75, easing: "easeOutQuad"});    	
				}
				*/
			}
			$("a[rel=kd_tab_a"+tabPath+"]").trigger('click');
			return true;
		}
	},
	/* !SEND FILE TO EDITOR */
	sendFileToEditor : function(myFileNameWithPath, optionalName) {
		if(!__k.base._ready){
			__k.utils.loading("We're moving our backend servers today, service is temporarily unavailable! Sorry. Please bear with us and check our updates on <a href=\"http://twitter.com/kodingen\" target=\"_blank\">Twitter</a> [close]", 15000, true);
		}else{
			__k.layout.section.middle.close();
			if(!__k.utils.isTabOpen(myFileNameWithPath)) { 
				__k.utils.openInValidEditor(myFileNameWithPath, optionalName);
			}
		}
	},
	createTabContainer : function(fileName, data, myFileNameWithPath, app) {
		
		//DEPRECATED
		//if request comes for upload tab
		//compare = '1b3281f0e4108dfa816ebe028d910472';
		//result = fileName.match(compare);
		//upload_pre = "<span class='none'>1b3281f0e4108dfa816ebe028d910472</span>";
		
		//if(result == '1b3281f0e4108dfa816ebe028d910472'){		
		//	fileName = fileName.replace(upload_pre,"") ;
		//}
		
		//truncate file names longer than 30 chars
		if (fileName.length > 30){
			pre = fileName.substr(0, 8); 
			suf = fileName.substr(-8, 8);
			fileName = pre+"..."+suf;
		}
		
		//if(result == '1b3281f0e4108dfa816ebe028d910472'){
			//fileName = upload_pre +"File upload to: "+ fileName ;
			//fileName = upload_pre +"File Upload";
		//}
		
		sid = Math.floor(Math.random()*10000000010);

		$("#kd_tabs").append("<div id='fragment-"+sid+"' class='"+app+"' rel='"+__k.utils.createDecentSelector(myFileNameWithPath)+"' path='"+myFileNameWithPath+"'>"+data+"</div>");
		$("#kd_tabs").tabs( 'add' , '#fragment-'+sid, fileName );
		$("#kd_tabs>ul>li:last>a").attr({
			title: myFileNameWithPath, 
			rel: "kd_tab_a"+__k.utils.createDecentSelector(myFileNameWithPath)
		});
	},
	createDecentSelector : function(mySelector) { 
		var my_path_key = '_';
		return mySelector.replace(/\.| |!|@|\#|\$|\%|\^|\&|\*|\(|\)|\/|\|/gi, my_path_key);
	},
	extensions : {
		bespin			: __k.app_defaults.extension_sets.code_files,
		codemirror		: __k.app_defaults.extension_sets.code_files,
		ymacs			: __k.app_defaults.extension_sets.code_files,
		"JayCut Mixer"	: __k.app_defaults.extension_sets.video_files,
		jmedia 			: ["psd","qt","qtif","qif","qti","tif","tiff","aif","aiff","aac","au","gsm","mid","midi","snd","wav","3g2","mp3","asx","asf","ra","ram","mpg","mpeg","mp4","m4a","mov","3gp","avi","wmv","flv","swf","wma","rm","rpm","rv","smi","smil","xaml"],
		download 		: ["zip","gz","bz2","tar","7zip","rar","gzip","bzip2","arj","cab","chm","cpio","deb","dmg","hfs","iso","lzh","lzma","msi","nsis","rpm","udf","wim","xar","z","jar","ace","7z","uue"],
		"Pixlr Express"	: ["png","gif","jpg","jpeg","bmp","svg","psd"],
		"Pixlr Editor" 	: ["png","gif","jpg","jpeg","bmp","svg","psd"],
		own				: ["phpmyadmin","mysqlquickadmin","sqlite","postgre","post_app","account","client","pixlr","upload","httpwebserver","pdf","download"]
	},
	context_extensions : {
		
		jmedia 		: ["psd","qt","qtif","qif","qti","tif","tiff","aif","aiff","aac","au","gsm","mid","midi","snd","wav","3g2","mp3","asx","asf","ra","ram","mpg","mpeg","mp4","m4a","mov","3gp","avi","wmv","flv","swf","wma","rm","rpm","rv","smi","smil","xaml"],
		extract 	: ["zip","gz","bz2","tar","7zip","rar","gzip","bzip2","arj","cab","chm","cpio","deb","dmg","hfs","iso","lzh","lzma","msi","nsis","rpm","udf","wim","xar","z","jar","ace","7z","uue"],
		picture 	: __k.app_defaults.extension_sets.image_files,
		own			: ["phpmyadmin","mysqlquickadmin","sqlite","postgre","post_app","account","client","pixlr","upload","httpwebserver","pdf","download"]
		
	},
	openInValidEditor : function(myFileNameWithPath, optionalName) { 
	
		var ext = __k.utils.returnExtension(myFileNameWithPath) || "txt",
			filename = __k.utils.returnFileFullName(myFileNameWithPath);
			
		//optionalName = optionalName || __k.utils.returnFileName(myFileNameWithPath);
		ext = ext.toLowerCase();
		
		var editor = [],
			taskListener = true;
		
		$.each(__k.utils.extensions, function(name,val) {
			$.each(val, function(i,v) {
				if (v === ext) {
					editor.push(name);
				}
			});
		});
		
		//default app is bespin
		editor[0] = (editor.length === 0) ? "bespin" : editor[0] ;

		switch (ext){
			case "httpwebserver" :
				taskListener = false;		
			break;
			default:
		}
		//console.log(editor);
		if(editor.length === 1){
			__k.utils.run_editor(myFileNameWithPath, taskListener, editor[0]);
		}else{
			if(__k.user.ui_states === null || typeof __k.user.ui_states["open_" + ext] === "undefined"){
				__k.quickMenu.loadData(__k.base.quickMenu.application_selector,{ p : myFileNameWithPath, t : taskListener, ext : ext, editors : editor.join()});
			}else{
				__k.utils.run_editor(myFileNameWithPath, taskListener, __k.user.ui_states["open_" + ext]);
			}
		}		
	},
	run_editor : function(myFileNameWithPath, taskListener, editor) {

		var ext = __k.utils.returnExtension(myFileNameWithPath) || "txt",
			filename = __k.utils.returnFileFullName(myFileNameWithPath);

		if (taskListener){
			var params = {"operation" : "publish_path_to_url", "path" : myFileNameWithPath};
			$.post(__k.base.ajaxUrl.def, params, function(d) {
				if (typeof d === "object" && typeof d.taskId !== "undefined"){
					__k.utils.task_memo[d.taskId] = {};
					__k.utils.task_memo[d.taskId]["input"] = params;
					__k.utils.task_memo[d.taskId]["command"] = d;
				}
				__k.utils.taskListener(d.taskId, d.cmd, function(r) {
					if(d !== null || typeof d === "object") { 
						var file_location = r.response[1];
						switch (editor) {
							case "jmedia" :
								var inner_params = {"p" : myFileNameWithPath, "loc" : file_location};
								$.post("/kodingen/kd_includes/"+editor+".enter.php", inner_params, function(data) {
									__k.utils.createTabContainer( filename, data, myFileNameWithPath, editor);	
								});
							break;
							case "download" :
								var params = {"operation" : "publish_path_to_url", "path" : myFileNameWithPath};
								__k.utils.save_prefs(__k.base.ajaxUrl.def,	params);
							break;
							case "Pixlr Express" :
								var data = '<iframe class="bespin_container" src="' + __k.base.editors.pixlr_express + '?image='+encodeURIComponent(file_location)+'&org_image='+encodeURIComponent(myFileNameWithPath)+'&referrer=Kodingen&loc=en&target=http://' + top.location.host + '/kodingen/kd_includes/pixlr.exit.php" frameborder="0"></iframe>';
								__k.utils.createTabContainer( filename, data, myFileNameWithPath, "pixlr");
							break;
							case "Pixlr Editor" :
								var data = '<iframe class="bespin_container" src="' + __k.base.editors.pixlr_editor + '?image='+encodeURIComponent(file_location)+'&org_image='+encodeURIComponent(myFileNameWithPath)+'&referrer=Kodingen&loc=en&target=http://' + top.location.host + '/kodingen/kd_includes/pixlr.exit.php" frameborder="0"></iframe>';
								__k.utils.createTabContainer( filename, data, myFileNameWithPath, "pixlr");
							break;
							case "JayCut Mixer" :
								//var data = '<iframe class="bespin_container" src="' + __k.base.editors.jaycut + '?image='+encodeURIComponent(file_location)+'&org_image='+encodeURIComponent(myFileNameWithPath)+'&referrer=Kodingen&loc=en&target=http://' + top.location.host + '/kodingen/kd_includes/pixlr.exit.php" frameborder="0"></iframe>';
								var data = '<iframe class="bespin_container" src="' + __k.base.editors.jaycut + '" frameborder="0"></iframe>';
								__k.utils.createTabContainer( filename, data, myFileNameWithPath, "jaycut");
							break;
							case "bespin" :
								var data = '<iframe class="bespin_container" src="kodingen/kd_includes/'+editor+'.enter.php?p='+encodeURIComponent(file_location)+'&org_p='+encodeURIComponent(myFileNameWithPath)+'&ext='+__k.utils.returnExtension(myFileNameWithPath)+'" frameborder="0"></iframe>';
								__k.utils.createTabContainer( filename, data, myFileNameWithPath, "bespin");
								__k.layout._bespinSizeFix();
							break;
							case "video_compression" :
								var data = '<iframe class="bespin_container" src="http://sinanyasar.com/videocompress/?file='+encodeURIComponent(file_location)+'&org_p='+encodeURIComponent(myFileNameWithPath)+'&ext='+__k.utils.returnExtension(myFileNameWithPath)+'&key=12374861203846123" frameborder="0"></iframe>';
								__k.utils.createTabContainer( filename, data, myFileNameWithPath, "bespin");
								__k.layout._bespinSizeFix();
							break;
							default:
								var data = '<iframe class="bespin_container" src="kodingen/kd_includes/'+editor+'.enter.php?p='+encodeURIComponent(file_location)+'&org_p='+encodeURIComponent(myFileNameWithPath)+'&ext='+__k.utils.returnExtension(myFileNameWithPath)+'" frameborder="0"></iframe>';
								__k.utils.createTabContainer( filename, data, myFileNameWithPath, editor);
								__k.layout._bespinSizeFix();
						}
					}else{
						$.growlUI('Error', 'We couldn\'t get this file\'s contents','growl_warning');
					}
					return delete __k.utils.task_memo[d.taskId];
				});
			},"json");
		}else{
			var inner_params = {"p" : myFileNameWithPath};
			$.post("/kodingen/kd_includes/"+ext+".enter.php", inner_params, function(data) {
				__k.utils.createTabContainer( filename, data, myFileNameWithPath, editor);	
			});
		}
	},
	convertToCodemirror : function(textarea_id, ext){

	},
	openTestTree : function(){
	/*
		$("#ftp_filetree_cover").fadeOut(400,function(){
			$("#ftp_filetree_cover").remove();
			$("#ft_quickMenu_panel_handle").trigger("click");
			$("#ft_avatarMenu_panel_handle").trigger("click");
		});
	*/
	},
	check_if_logged_in : function(id,login) {
		__k.user.data.id = parseInt(__k.user.data.id, 10);
		id = parseInt(id, 10);
		if(id !== 0){
	  		__k.user.is_logged_in = true;
	  		__k.user.data.user_login = login;
		}

		if(__k.user.data.id !== id){
		  	if(id !== 0){
		  		$.growlUI('You have succesfully logged in', 'Happy coding!','growl_smile');
		  		$("#trigger_logout").show();
		  	}else{
	  			$.growlUI('You have succesfully logged out', 'Have a nice day!','growl_smile');	
				$("#trigger_logout").hide();
		  		__k.user.is_logged_in = false;
		  		__k.user.data.user_login = "guest";
			}
			__ft1.init_tree();
			this.get_avatar_block();
			this.retrieve_bottom_menu();
			__k.quickMenu.reset();
			__k.user.clear_ui_states();
			__k.utils.taskLogger.clear()
			__k.layout.onResize();
		}
	},
	get_avatar_block : function() {
		var hide_show = ($("#ft_avatarMenu_panel:hidden").length === 1) ? "none" : "block";
		
		$.ajax({
		  type: "GET",
		  url: "kodingen/kd_includes/filetree/avatar_block.php",
		  cache: false,
		  data: "rbh=1",
		  success: function(html){
	
			//GET AVATAR BLOCK CONTENT
		    $("#ft_avatar_block_holder").html(html);
			$("#ft_avatarMenu_panel").css("display", hide_show);
			
		  }
		});
	},
	retrieve_bottom_menu : function() {
		var hide_show = ($("#ft_bottom_quickMenu:hidden").length === 1) ? "none" : "block";
		$.ajax({
			type: 'POST',
			url: "kodingen/kd_includes/filetree/filetree_bottom_expand_panel.php",
			cache: false,
			data: "rbh=1",
			success: function(html){
				$("#filetree_bottom_menu").remove();
				$("#leftPane .tree_holder").after(html);
				$("#ft_quickMenu_panel_content").css("display", hide_show);
			}
		});
	},
	avatar_notification : function(amount) {
		var that = this;
		if ( $("#avatar_message_count").length === 1){
			var o = parseInt( $("#avatar_message_count").html(), 10 );
		}else{
			var o = 0;
		}
	
		if ( o !== amount ){
			that.get_avatar_block();
		}
	},
	logout : function(href) {
		var that = this;
		$.ajax({
			type: 'POST',
			url: href,
			cache:false,
			success: function(data){
				$.growlUI('You have succesfully logged out', 'Have a nice day!','growl_smile');
/*
				var t = setTimeout(function() {
					top.location.reload();	
				},1000)
*/
				
				that.get_avatar_block();
				that.retrieve_bottom_menu();
				__k.user.get_data();
				__k.utils.openInCommunity('http://kodingen.com/w');
				__ft1.init_tree();
			} 			
		}); 
	},
	beforeUnload : function(event){
		event.preventDefault();
		//ONUNLOAD CHECK IF THERE ARE TABS OPEN AND WARN USER
		function openTabsAmount(){
			var openedTabs = $("#kd_tabs ul li").length;
			return openedTabs;
		}
		if(openTabsAmount() > 1){
			var msg = 	"A Kodingen Warning:\n\n" +
					"You have open tabs, your unsaved changes might be lost if you navigate away or reload the window.";
			event.returnValue = msg;
		}
		
		/*
			var $dialog = $("div#kodingen_modal_box");
			
			$dialog.html("Your unsaved changes might be lost if you close the window, click cancel to go back to Kodingen or OK to continue.")
			$dialog.dialog({
				title : "Are you sure?",	
				bgiframe: true,
				resizable: false,
				modal: true,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				},
				buttons: {
					'Ok': function() {
						$(this).dialog('close');
					},
					'Cancel': function() {
						$(this).dialog('close');
						event.preventDefault();
						return false;
					}
				},
				close: function() {
					$(this).dialog('destroy');
				}
			}).show(400);
		*/
	},
	avatarMenuToggle : function() {
		if($("#ft_avatarMenu_panel:hidden").length == 1){
			this.openAvatarMenu();
		}else{
			this.closeAvatarMenu();
		}
	},
	openAvatarMenu : function() {
		if($("#ft_avatarMenu_panel:hidden").length == 1){
			$("#ft_avatarMenu_panel").animate({"height":"show"}, 200, function(){
				//arrange filetree height
				$("#ft_avatarMenu_panel_handle").addClass("toTop");
				a = $("#ft_avatarMenu_panel").height();
				h = $(".tree_holder").height();
				f = h - a;
				$(".tree_holder").css("height",f);
			});
		}
	},
	closeAvatarMenu : function() {
		a = $("#ft_avatarMenu_panel").height();
		$("#ft_avatarMenu_panel").animate({"height":"hide"}, 200, function(){
			//arrange filetree height
			$("#ft_avatarMenu_panel_handle").removeClass("toTop");
			h = $(".tree_holder").height();
			f = h + a;
			$(".tree_holder").css("height",f);
		});
	},
	onCommunityUnload : function() {
		__k.utils.loading("Working...");
	},
	openInCommunity : function (link){
		$("#kd_community_tab_selector").trigger('click');
		$("#kd_community_tab").attr("src", link);
	},
	accordionThem : function (idToBeOpened){
		// Accordion Module , used for treeMenu Console
		if($("#"+idToBeOpened).hasClass("oneOpen")){
			$("#"+idToBeOpened).siblings(".app_store_even_row, .app_store_odd_row,").animate({"height": "toggle", "opacity": "toggle"}, 400);
		}
		//var t = setTimeout(function(){
			$("#accContent_"+idToBeOpened).animate({"height": "toggle"}, 150);
			$("#accContent_"+idToBeOpened).toggleClass("accOpened");
			$("#accContent_"+idToBeOpened).siblings(".accClass").each(function (i) {
				if ($(this).hasClass("accOpened") && this.id != "accContent_"+idToBeOpened){
					$("#"+this.id).animate({"height": "toggle"}, 150);
					$("#"+this.id).removeClass("accOpened");
				}
			});
		//},500);
	},
	proxyParent : function(evt) {
		$("input#proxy_focus").trigger("focus");
	},
	unescapeHTML : function (html) {
		var htmlNode = document.createElement("DIV");
		htmlNode.innerHTML = html;
		if(htmlNode.innerText)
		return htmlNode.innerText; // IE
		return htmlNode.textContent; // FF
	}
	
};


/* !KODINGEN USER */
__k.user = {
	/* THIS IS DECLARED HERE, AND SET ON PAGE LOAD WITH WP*/
	data 		: {},
	is_logged_in: false, 
	get_data	: function() {
		var that = this;
		$.post(__k.base.ajaxUrl.def, { operation : "_getUserDataForDOM"}, function(d) {
			that.data = d;			
		});
	},	
	set_initial_ui_states : function(states) {
		var that = this;
		$.post(__k.base.ajaxUrl.def, { operation : "get_ui_state", identifier : "ui_states"}, function(d){
			if(d !== null){
				d = JSON.parse(d);
				that.ui_states = d;
			}
		},"json");
	},
	set_ui_state : function(id, data, callback) {
		var that = this;
		that.ui_states[id] = data;
		if(that.is_logged_in) {
			$.post(__k.base.ajaxUrl.def, { operation : "save_ui_state", identifier : 'ui_states', data : JSON.stringify(that.ui_states) },function() {
				if(typeof callback !== "undefined"){
					callback.call(this);
				}
			},"json");
		}
	},
	get_ui_state : function(id, callback) {
		var that = this;
		$.post(__k.base.ajaxUrl.def, { operation : "get_ui_state", identifier : "ui_states"}, function(d){
			d = JSON.parse(d);
			if(typeof callback !== "undefined" && typeof d[id] !== "undefined" ){
				callback.call(this,d[id]);
			}
			that.ui_states[id] = d[id];
		},"json");
	},
	reset_ui_state : function(id){
		var that = this;
		if (typeof that.ui_states["open_" + id] !== "undefined"){
			delete that.ui_states["open_" + id];
		}
	},
	clear_ui_states : function(){
		this.ui_states = {};
	},
	ui_states	: {}
};

/* !QUICKMENU */
__k.quickMenu = {

	_aSheet : '<div class="screen"></div>',
	_sheetClass : 'screen',
	$cSheet : {},
	_scroller : "#quick_menu",
	_holder : "#middlePane",
	_isNew : true,
	_isLocked : false,
	loadData : function(url, args, callback){
		var that = this;
		if (typeof url === "object" && !that._isLocked)
		{
			that.initRenderer(url,callback);
		}
		else if (that._isLocked)
		{
			__k.layout.section.middle.open();
			__k.utils.loading("Uploader is in action, please wait till your files finish uploading", 5000);
		}
		else
		{
			$.post( url, args, function(data) {
				that.initRenderer(data,callback);
			},"json");
		}
	},
	slideRight : function(callback) {
		//check the home node of content
		//by checking the menu width
		//if it is start sheet, close quickmenu
		//otherwise just slide to previous sheet
		var that = this,
			screen_amount = $(this._scroller).find('div.screen').length;
		
		if (screen_amount > 1){
			var that = this,
				$pSheet = this.$cSheet.prev(),
				w = this.$cSheet.width(),
				sw = $(this._scroller).width();

			this.$cSheet.closest(this._holder).animate({ scrollLeft: "-="+w+"px"},400, function() {
				that.$cSheet.remove();
				that.$cSheet = $pSheet;
				$(that._scroller).width(sw-w);
			});
		}else{
			__k.layout.section.middle.close();
			if(!that._isLocked){
				$(that._scroller).fadeOut(400);
			}
		}
		
		if(typeof callback !== "undefined") {
			callback.call(that);
		}
		
	},
	slideLeft : function(json,operation) {
		//get a sheet width
		var pw = __k.quickMenu.$cSheet.width();
		//tell that menu is in use not initializing
		__k.quickMenu._isNew = false;
		//load data into menu to initialize new sheet
		__k.quickMenu.loadData(json,operation,function(data) {
			//assign previous sheet, and set total width of scroller
			var $pSheet = this.$cSheet.prev(),
				w = this.$cSheet.prev().width(),
				sw = $(this._scroller).width();
			$(this._scroller).width(sw+w);
			//to go secure resize all sheets to current menu width
			$('.'+__k.quickMenu._sheetClass).width(pw);
			//scroll menu to newly added sheet
			$(this._holder).animate({ scrollLeft: "+="+w+"px"},400);
			
			//fill label of back button if there is no label provided in json
			if(this.$cSheet.find('span.back_button').html() === ""){
				var backLabel = (data.header.left_button === "") ? $pSheet.find('h2.sheet_title').html() : data.header.left_button;
				this.$cSheet.find('span.back_button').html(backLabel);
			}
		});
	},
	initRenderer : function(data,callback) {
		__k.utils.startTime();
		var that = this;
		
		if (typeof data === "undefined") { 
			return false;
		}
		
		that._memo = "";
		this._clearRegistry();
		that.$cSheet = $(that._aSheet);
		that._recursive_template_finder(data);
		that.$cSheet.html(that._memo);
		that._put_data(data,that.$cSheet);

		if(that._isNew){
			$(that._holder).animate({ "scrollLeft" : "0px" }, 400, function() {
				$(that._scroller).width($(that._holder).width());
				$(that._scroller).fadeOut(400, function() {
					$(that._scroller).html(that.$cSheet).fadeIn(400);
				});
			});
		}else{
			$(that._scroller).append(that.$cSheet);
		}
		
		that._isNew = true;
		__k.layout.section.middle.open();
		$(that._scroller).find(".qm_temp_loader").fadeOut(400, function() {
			$(this).remove();
		});
		
		if(typeof callback !== "undefined") {
			callback.call(that,data);
		}
	},
	_recursive_template_finder : function(data,a,n) {
		var that = this,
			last = data.length,
			$temp;
			
		a = a || false;
		n = n || '';
		$.each(data, function(name,val) {
			if(typeof val === "object"){
				var el = 'div';
				if (typeof val.template !== "undefined"){
					val.template = val.template || "default";
					var section = '';
					if (typeof __k.qmTemplates["__"+name+"_templates"] === 'object'){section = name;}
					else if (typeof __k.qmTemplates["__"+n+"_templates"] === 'object'){section = n;}
					val.section = section;
					that._memo += '<'+el+' class="'+section+'" alt="'+section+'" data="'+that._registry_record(val)+'">';
					that._memo += __k.qmTemplates._get_template.call(__k.qmTemplates,val,section);
				}
				$.each(val, function(n,v) {
					if ($.isArray(v)){
						that._memo += '<div>';
						that._recursive_template_finder(v,true,n);
						that._memo += '</div>';
						that._memo += __k.qmTemplates._get_template_footer.call(__k.qmTemplates,val,section);
					}
				});
				that._memo += '</'+el+'>';
			}
		});
	},
	_put_data : function(data,$sheet) {
		var that = this;
		$sheet.find('*[data]').each(function(i,val) {
			var section = $(this).attr('alt');
			__k.qmTemplates["_render_"+section].call(__k.qmTemplates,that.registry[i],this);
		});
	},

	_memo : '',
	registry : {},
	_regId : 0,
	_registry_record : function(data) {
		this.registry[this._regId] = data;
		this._regId++;
		return this._regId;
	},
	_clearRegistry : function() {
		this._regId = 0;
		this.registry = {};
	},
	resize : function() {
		var tw = $(this._holder).width(),
			sa = $(this._scroller).find('.'+this._sheetClass).length;
		
		$(this._scroller).width(sa*tw);
		$('.'+this._sheetClass).width(tw);
		$(this._holder).scrollLeft(sa*tw-tw);
	},
	reset : function() {
		var that = this;
		$(that._holder).animate({ "scrollLeft" : "0px" }, 400, function() {
			$(that._scroller).width($(that._holder).width());
			$(that._scroller).fadeOut(400, function() {
				$(that._scroller).html('');
				__k.layout.section.middle.close();
			});
		});
	}

};

/* !QUICKMENU TEMPLATE ENGINE */
//THIS OBJ CONTAINS THE HTML TEMPLATES USED IN QUICKMENU
__k.qmTemplates = {

	_get_template : function(data,section) {
		var template = data.template,
			templates	= this["__"+section+"_templates"],
			thtml = "",
			$temp = "",
			tclose = "";

		$.each(templates,function(i,t) {
			if (template === t.name){
				thtml += t.html;
			}
			/*
			if (template+"_footer" === t.name){
				thtml += t.html;
			}
			*/
		});

		return thtml;
	},
	_get_template_footer : function(data,section) {
		var template = data.template+"_footer",
			templates	= this["__"+section+"_templates"],
			thtml = "",
			$temp = "",
			tclose = "";
		$.each(templates,function(i,t) {
			if (template === t.name){
				thtml = t.html;
			}
		});
		return thtml;
	},
	_alt_content : function(data,item) {
	},

	_render_header	: function(data,item) {
		$(item).find('*[alt]').each(function() {
			var alt = $(this).attr('alt');
			$(this).html(data[alt]);
		}).end().find('span.back_button').bind('click',function() {
			__k.quickMenu.slideRight();
		});
		
		if(typeof data.right_button === "object"){
		
		//put header right button here
		}
		
	},
	_render_sheet	: function(data,item) {
		if (data.template === "form")
		{
			$(item).wrapInner(document.createElement("form"));
		}

		__k.quickMenu.$cSheet.bind('mousewheel', function(event, delta) {
            var dir = delta > 0 ? -1 : 1,
                vel = Math.abs(delta),
            	step = vel*25,
            	actP = $(this).scrollTop(),
            	newP = dir*step+actP;

            $(this).scrollTop(newP);
            return false;
	    });
	},
	_render_tabbar	: function(data,item) {
	},
	_render_group	: function(data,item) {
		$(item).find('[alt]').each(function() {
			var $item	= $(this),
				alt 	= $item.attr('alt');
			//RENDERING AND BINDING EVENTS TO ITEM'S SUBELEMENTS
			if( alt === 'title' || alt === 'description' )
			{
				$(this).html(data[alt]);
			}
		});
		
		if (data.template === "form"){
			$(item).wrapInner(document.createElement("form"));
		}else if (data.template === "custom"){
			if(typeof data.custom_content.content !== "undefined"){
				$(item).find(".custom_group").html(data.custom_content.content);
			}else{
				$.post(data.custom_content.url , data.custom_content.params, function(d) {
					$(item).find(".custom_group").html(d);
				});
			}
		}
		
	},
	/* !ITEM RENDERERS START */
	_render_item	: function(data,item) {

		data.template = data.template || "default";

		//RENDERING ACCORDING TO ITEM TEMPLATE
		if(typeof this["_render_item_"+data.template] === "function"){
			this["_render_item_"+data.template].call(this,data,item);
		}
		
	},
	_render_item_default : function(data,item) {
		$(item).find('*[alt]').each(function() {
			var $item	= $(this),
				alt 	= $item.attr('alt');
			//RENDERING AND BINDING EVENTS TO ITEM'S SUBELEMENTS
			if( alt === 'title' )
			{
				$(this).html(data[alt].value);
				$(this).bind('click',function() {
					if(data[alt].action === "" || typeof data[alt].action === "undefined"){
						$(this).next().trigger('click');		
					}else{
						if(typeof __k.utils[data[alt].action] === "function"){
							window.__k.utils[data[alt].action].call(this,data[alt].value);
						}
					}
				});
			__k.qmTemplates._slide_long_label($item);
			}
			else if ( alt === 'option' )
			{
				__k.qmTemplates._render_option(data,$item);
			}
		});
		
	},
	_render_item_slider : function(data,item) {
		var _st = 0,
			unit = (typeof data.option.unit !== "undefined") ? data.option.unit : "" ;

		$(item).find('*[alt]').each(function() {
			var $item	= $(this),
				alt 	= $item.attr('alt');
			
			if(typeof data[alt].value !== undefined){
				//RENDERING AND BINDING EVENTS TO ITEM'S SUBELEMENTS
				if(alt === "option"){ 
					$(this).html(data[alt].value + " " + unit);
				}else{
					$(this).html(data[alt].value);
				}
				$(this).bind('click',function() {
					//alert(data[alt].action);
				});
			}
		});
		
		$(item).find('.slider').slider({
			range	: "min",
			step	: data.option.step,
			animate	: true,
			value	: parseInt(data.option.value,10),
			min		: parseInt(data.option.min,10),
			max		: parseInt(data.option.max,10),
			start	: function(event, ui) { _st = ui.value;	},
			slide	: function(event, ui) { $(item).find('.slider_value').html(ui.value + " " + unit); },
			change	: function(event, ui) { $(item).find('.slider_value').html(ui.value + " " + unit); },
			stop	: function(event, ui) {
				var params = data.option.action.params;
				__k.utils.save_prefs("",params, function(r,s){
					if(r.result === 1){
						//__k.utils.success_msg();
					}else if(r.result === 0){
						$(item).find('.slider').slider('value', _st);
					}
				});
			
			}

		});
		
	},
	_render_item_inner_input : function(data,item) {
		$(item).find('*[alt]').each(function() {
			var $item = $(this),
				alt = $item.attr('alt'),
				ac = '"autocomplete="off"',
				required= (data.option.required)? "required" : "",
				val_type= data.option.validation_type || "";
			//put label content and set for attribute
			$item.html(data[alt].value).attr('for',data.option.name);

			//put form elements according to their types
			switch (data.option.type) {

				case "select" :
					var content = '<select '+ac+' class="select fr" name="'+data.option.name+'">';
					$.each(data.option.values, function(i,v) {
						content += "<option value='"+v.value+"'>"+v.text+"</option>";
					});
					content += "</select>";
					
					var $content = $(content);
					$content.val(data.option.selected_value);
					$item.after($content);
					
					if (typeof data.option.action !== "undefined"){
						if (typeof data.option.action.params !== "undefined"){
							var params = data.option.action.params;
							$content.change(function() {
								params.set_to = $content.val();
								params.key = data.option.name;
								__k.utils.save_prefs(data.option.action.target_url, params, function(r,s){
									if(r.result === 1 || r.status === "ok"){
										
									}else if(r.result === 0||r.status === "error"){
										$.growlUI('Error', r.errtext,'growl_warning');
									}
								});
							});
						}
					}

				break;

				case "textarea" :
					$item.after('<textarea '+ac+' class="'+data.option.type+' '+required+' '+val_type+'" name="'+data.option.name+'" type="'+data.option.type+'">'+data.option.value+'</textarea>');
					//TEMP FIX
					$item.closest('.item').height(90);
				break;

				case "radio" :
					var checked = (typeof data.option.checked !== "undefined" && data.option.checked === "true") ? true : false;
					var $input = $('<input class="'+data.option.type+' fr '+required+' '+val_type+'" '+ac+' name="'+data.option.name+'" type="'+data.option.type+'" value="'+data.option.value+'"/>');

					$item.after($input);
					$input.hide().after('<div class="fr iradio_wrapper"><span class="iradio"></span></div>');

					var pitem = $input.closest('.item'),
						pgroup = $input.closest('.group');
						
					pitem.addClass("pointer");
					pitem.click(function() {
						if(pitem.find('input[type=radio]').attr('checked')){
							pitem.find('input[type=radio]').attr('checked',false);
							pgroup.find('span.iradio').css("background-position","left bottom");
							__k.qmTemplates._block_dependent_child(data,$input);
							return false;
						}else{
							pitem.find('input[type=radio]').attr('checked',true);
							pgroup.find('span.iradio').css("background-position","left bottom");
							pitem.find('span.iradio').css("background-position","left top");
							__k.qmTemplates._block_dependent_child(data,$input);
							return false;
						}
					});
					if(checked){
						var t = setTimeout(function() {
							pitem.find('span.iradio').trigger('click');
						},500);
					}else{
						if(pitem.is(":first-child")){
							var t = setTimeout(function() {
								pitem.find('span.iradio').trigger('click');
							},500);
						}
					}
					
				break;
				case "password" :
					$item.after('<input class="text fr '+required+' '+val_type+'" '+ac+' name="'+data.option.name+'" type="'+data.option.type+'" value="'+data.option.value+'"/>');
				break;
				default :
					$item.after('<input '+ac+' class="'+data.option.type+' fr '+required+' '+val_type+'" name="'+data.option.name+'" type="'+data.option.type+'" value="'+data.option.value+'"/>');
			}
			

			
			__k.qmTemplates._slide_long_label($item);
			__k.qmTemplates._check_dependent_parent(data,$item.next());
		});
		
	},
	_render_item_form_button_block : function(data,item) {
		var $item	= $(item);
		
		$.each(data.buttons, function(i,val) {
			var $button = $('<button class="button" alt="title"></button>');
			var $title = $('<div style="float: left; display: block; position: relative; height: 20px; line-height: 20px;">'+val.value+'</div>');
			
			$item.append($button).addClass('center').css('padding',0);
			$button.append($title);
			
			var $loader_holder = $('<div style="margin: 0pt 5px 0pt -15px; padding: 2px 0pt; float: left; display: block; position: relative; height: 16px; width: 16px;"></div>');
			var $loader_img = $('<img src="/kodingen/css/css_images/_newGui/qm_ajax_loader_button.gif" />');

			var $form = $button.closest('form');
			
			$form.bind('submit', function(e) {
				e.preventDefault();
				$form.find('button.button').eq(0).trigger('click');
				return false;
			});
			
			$button.bind('click', function(e) {
				e.preventDefault();
				
				switch (val.type) {
				
					case "button" : 
						var $form = $button.closest('form'), p = $form.serializeArray(), submenu = false;
						
						$form.find('.item.error').css('background-color','#fff').removeClass('error');
						
						$.each(val.params, function(n,v) {
							var a = { "name": n, "value" : v };
							submenu = ( n === "submenu" && v === "true" ) ? true : false ;
							p.push(a);
						});
						
						$form.validate();
		
						if ( $form.valid() ) {
							$button.prepend($loader_holder);
							$loader_holder.append($loader_img);
							
							__k.utils.save_prefs(val.post_url,p,function(response,status) {
								if(submenu){
									__k.quickMenu.loadData(response);
									$loader_holder.remove();
								}
							}); 
						}else{
							$button.find('div').animate({'color':'red'},400,function() {
								$(this).animate({'color':'#151515'},400);
								__k.utils.loading('Please check all required fields!',1500);
							});
						}
					break;
					case "cancel" : 
						__k.quickMenu.slideRight();
						$(__ft1.options._tree).unblock();
					break;
					default:
				
				}
				
				return false;
			});
		});
	},
	_render_item_app_store : function(data,item) {
		$(item).find('*[alt]').each(function() {
			var $item	= $(this),
				alt 	= $item.attr('alt');
			//RENDERING AND BINDING EVENTS TO ITEM'S SUBELEMENTS
			if( alt === 'title' )
			{
				var target = (data.link.search(/javascript:/i) === -1) ? "_blank" : "" ;
				data.link = data.link || "";

				$item.html(data[alt].value).append('<a class="qm_ext_link" target="'+target+'" href="'+data.link+'"><img src="'+__k.qmTemplates.__ext_link_icon+'" /></a>');
				$item.bind('click',function() {
					if(data[alt].action === "" || typeof data[alt].action === "undefined"){
						$item.next().trigger('click');		
					}else{
					}
				});
			}
			else if ( alt === 'option' )
			{
				__k.qmTemplates._render_option(data,$item);
			}
			else if ( alt === 'icon' )
			{
				data.icon = data.icon || __k.qmTemplates.__app_store_default_icon;
				
				var $icon = $('<img src="'+data.icon+'" class="item_icon_img"/>');
				$item.append($icon);
			}
			else if ( alt === 'description' )
			{	
				$item.html('<div class="_inner_con">'+data[alt]+'</div>');
				var t;
				$item.toggle(function() {
					var h = $item.find('div._inner_con').height();
					if(h > 44){
						$item.find('div._inner_con').attr('title','Click to read more...');
						$item.animate({"height":h},200);
					}
				},function() {
					$item.animate({"height": "44px"},200);
				});
			}
			else if ( alt === 'rating' && typeof data[alt] !== "undefined" )
			{
				data[alt].value = (isNaN(parseFloat(data[alt].value))) ? 0 : parseFloat(data[alt].value);
				var pr = data[alt].value*100/5;
				$item.progressbar({
					value: pr
				});
				$item.attr('title', data[alt].value.toFixed(2) + '/5 out of '+data[alt].total+' ratings.');

			}
			else
			{
				$item.html(data[alt]);
			}
			
		});
		
	},
	_render_item_chart : function(data,item) {
		$(item).find('img').attr("src","http://chart.apis.google.com/chart?"+$.param(data.chart_options));
	},
	_render_item_progress_bar : function(data,item) {
		$(item).find('.progress_bar').progressbar({
			value: data.option.value
		});

		$(item).find('*[alt]').each(function() {
			var $item	= $(this),
				alt 	= $item.attr('alt');
			
			if(typeof data[alt].value !== undefined){
				//RENDERING AND BINDING EVENTS TO ITEM'S SUBELEMENTS
				if ( alt === "option" ) {
					$(this).html(data[alt].value_text);
				}else{
					$(this).html(data[alt].value);
				}
				if ( $(this).hasClass("list_info") ){
					$(this).removeClass("list_info").css("margin-right","15px");
				}else if ( $(this).hasClass("list_item") ){
					$(this).removeClass("list_item").removeClass("clear").addClass('fl');
				}
				
				$(this).bind('click',function() {
					//alert(data[alt].action);
				});
			}
		});

	},
	/* !OPTION RENDERERS START */
	_render_option : function(data,$item) {
		var alt = "option";
		switch(data[alt].action.type){
			case "info" :
				$item.html(data[alt].value).removeClass("list_action").addClass("list_info");
				$item.prev().css('position','relative').addClass('list_info_title');
			break;
			case "run" :
				$item.html(data[alt].value);
				var params = data[alt].action.params;
				$item.bind('click',function() {
					var $loader = $('<div class="qm_temp_loader"></div>');
					$item.after($loader);
					
					switch(params.js_operation){
						case "run_editor" :
							__k.user.set_ui_state("open_" + __k.utils.returnExtension(params.path), params.editor);
							__k.utils.run_editor(params.path, params.taskListener, params.editor);
						break;
						default:
					}
					
					__k.quickMenu.slideRight();	
					
				});
			break;
			case "submenu" :
				$item.html(data[alt].value);
				$item.bind('click',function() {
					var $loader = $('<div class="qm_temp_loader"></div>');
					$item.after($loader);
					__k.quickMenu.slideLeft.call(this,data[alt].action.submenu_json,data[alt].action.params);	
					
				});
			break;
			case "submenu_submit" :
				$item.html(data[alt].value);
				$item.bind('click',function() {
					var that = this;
					var $loader = $('<div class="qm_temp_loader"></div>');
					$item.after($loader);

					var $form = $item.closest('form'),
						p = $form.serializeArray();
					
					$.each(p, function(n,v) {
						data[alt].action.params[v.name] = v.value;
					});

					//__k.utils.save_prefs(__k.base.ajaxUrl.def,p,function(response,status) {});
					__k.quickMenu.slideLeft.call(that,data[alt].action.submenu_json,data[alt].action.params); 
					
				});
			break;
			case "open" :
				$item.html(data[alt].value);
				$item.bind('click',function() {
					__k.utils.sendFileToEditor(data[alt].open_url+'.httpwebserver', data.title.value);
				});
			break;
			case "switch" :
				//CHECK IF IT IS FORM ELEMENT OR STANDALONE SWITCH
				var callback = true,
					input_name = data[alt].name;
				
				if (typeof data[alt].action.params === "undefined"){
					callback = false;
				}else{
					if(typeof data[alt].name === "undefined" || data[alt].name === ""){
						input_name = data[alt].action.params.operation;
					}
				}
				
				//PREPARE ITEM AND ITS HOLDER
				var $input = $("<input class='switch' autocomplete='off' type='checkbox' name="+input_name+" />");
				$item.removeClass('list_action').addClass('switch_parent').html($input);
				
				//SET INIT CLASSES AND STATES
				if( data[alt].value === "0" || data[alt].value === "" || data[alt].value === "false" ){
					$input.attr("checked",false);
				}else if(data[alt].value === "disabledfalse"){
					$input.attr("checked",false);
					$input.attr("disabled",true);
				}else if(data[alt].value === "disabledtrue"){
					$input.attr("checked",true);
					$input.attr("disabled",true);
				}else{
					$input.attr("checked",true);
				}
				
				//ben form elementiyim babam var mi bak
				//varsa ve aktif degilse beni kitle
				__k.qmTemplates._check_dependent_parent(data,$input);

				//SET CHECKBOX VALUE
				$input.val(data[alt].value);
				//CREATE SWITCH
				$input.iswitch({
					callback: function(element,state) {
						//ben parentmiyim bak eger kapaliysam
						//cocuumu kapat
						__k.qmTemplates._block_dependent_child(data,element);
						if(callback){
							var params = data[alt].action.params;
							params.set_to = state;
							params.key = data.option.name;
							__k.utils.save_prefs(data[alt].action.target_url,params, function(r,s){
								var $switch = element.next();
								if(r.result === 1 || r.status === "ok"){
									__k.utils.loading('Setting successfully changed',2500);	
								}else if(typeof r !== "object" || r.result === 0 || r.status === "error"){
									var b = (state) ? false : true;
									var a = (!state) ? 0 : -102;
									$switch.attr("class","jquery_iswitch switch"+b);
									$switch.css("background-position","left "+a+"px");
									element.attr("checked",b);
									$.growlUI('Error', r.errtext,'growl_warning');
								}
							});
						}
					}
				});
				
			break;
			default:
		}
	},
	_slide_long_label : function($item) {
		//LABEL SLIDER
		//if label is longer than its place holder slide it on mouse over
		//and on mouse out slide it back to org position
		if ($item.not('label')){return false;}
		$item.css('position','absolute');
		var ti;
		
		$item.mouseenter(function() {
			ti = setTimeout(function() {
				var iw = $item.outerWidth(),
					pw = $item.closest('.item').outerWidth(),
					nw = $item.next().outerWidth(),
					pl = pw - nw - 15,
					lm = pl-iw-20,
					du = -1*lm*10;
					
					if(iw > pl){
						$item.next().blur();
						if($item.parent().find('.item_left_transparency').length === 0){
							$item.before('<span class="item_left_transparency"></span>');
						}
						$item.animate({"backgroundColor": "#ffc"},400);
						$item.animate({"marginLeft": lm+"px"},du);
					}
			},1000);
		}).mouseleave(function() {
			clearTimeout(ti);
			var du = parseInt($item.css("margin-left"),10)*10*-1,
				t = setTimeout(function() {
					$item.animate({"backgroundColor": "#fff"},400);
					$item.animate({"marginLeft": "0px"},du);
					$item.next().focus();
				},1000);
		});
		
	},
	_block_dependent_child : function(data,$input) {
		//SEE IF ELEMENT HAS A DEPENDENT PARENT ELEMENT
		if (typeof data.option.child !== "undefined" ) {
			var $child = $input.closest('form').find("[name="+data.option.child+"]"),
				$citem = $child.closest('.item'),
				state = $input.is(":checked");
			__k.qmTemplates._block_item($citem,state);
		}
	},
	_check_dependent_parent : function(data,$input) {
		//SEE IF ELEMENT HAS A DEPENDENT PARENT ELEMENT
		if (typeof data.option.parent !== "undefined" ) {
			var $parent = $input.closest('form').find("[name="+data.option.parent+"]"),
				$item = $input.closest('.item'),
				state = $parent.is(":checked");
			__k.qmTemplates._block_item($item,state);
		}
	},
	_block_item : function(item,state) {
		if (state){
			item.unblock();
		}else{
			item.block();
		}
	},
	__app_store_default_icon : '/kodingen/css/css_images/_newGui/app_noicon_50x50.png',
	__ext_link_icon : '/kodingen/css/css_images/_newGui/external_link.png',
	/* !QUICKMENU TEMPLATES */
	__header_templates : [
		{
			name : 'default',
			html : 	'<span class="back_button" alt="left_button"></span>'+
					'<h2 class="sheet_title" alt="title"></h2>'+
					'<span class="action_button">+</span>'
		}

	],
	__sheet_templates : [
		{
			name : 'default',
			html : ''
		},
		{
			name : 'form',
			html : ''
		}
	],
	__tabbar_templates : [
		{
			name : 'default',
			html : ''
		}
	],


	//SHEET INNER TEMPLATES
	__group_templates : [
		{
			name : 'default',
			html : '<h3 class="group_title" alt="title"></h3>'
		},
		{
			name : 'default_footer',
			html : '<div class="group_description" alt="description"></div>'
		},
		{
			name : 'form',
			html : '<h3 class="group_title" alt="title"></h3>'
		},
		{
			name : 'form_footer',
			html : '<div class="group_description" alt="description"></div>'
		},
		{
			name : 'custom',
			html : '<h3 class="group_title" alt="title"></h3><div class="custom_group"></div>'
		},
		{
			name : 'custom_footer',
			html : '<div class="group_description" alt="description"></div>'
		}
	],
	//GROUP INNER TEMPLATES
	__item_templates : [
		{
			name : 'default',
			html : '<div class="list_item" alt="title"></div>'+
					'<div class="list_action" alt="option"></div>'
		},
		{
			name : 'app_store',
			html : '<table class="app_item">'+
						'<tr>'+
							'<td class="td_icon"><div class="item_icon" alt="icon"></div><div class="item_rating" alt="rating"></div></td>'+
							'<td class="td_meta"><div class="item_title fl" alt="title"></div><div class="item_desc" alt="description"></div></td>'+
							'<td class="td_action"><div class="list_action" alt="option"></div></td>'+
						'</tr>'+
					'</table>'
		},
		{
			name : 'form_button_block',
			html : ''
		},
		{
			name : 'inner_input',
			html : '<label class="list_label" alt="title"></label>'
		},
		{
			name : 'chart',
			html : '<img class="chart" src="" alt="chart"/>'
		},
		{
			name : 'progress_bar',
			html : '<div class="progress_bar_wrapper clear"><div class="progress_bar" type="text"></div></div>'+
					'<div class="list_item progress_bar_info clear" alt="title"></div>'+ 
					'<div class="list_info progress_bar_info fr" alt="option"></div>'
		},
		{
			name : 'slider',
			html : '<div class="list_item clear" alt="title"></div><div class="slider_value fr" alt="option"></div><div class="slider_wrapper"><div class="slider" type="text"></div></div>'
		}
	]

};


/*
////////////////////////////
/ dashboard                /	
/                          /
/                          /
////////////////////////////
/ top section              /	
////////////////////////////  M
/       /     /            /  A
/       /     /            /  I
/       /     /            /  N
/       / mid /            /  |
/ left  / dle / right      /  |
////////////////////////////  Container.
/                          /
/ bottom                   /
////////////////////////////
          

*/

/* !LAYOUT */
__k.layout = {

	winWidth		: 0,
	winHeight		: 0,
	contentHeight	: 0,
	duration		: 400,
	lpw				: 0,
	rpw				: 0,
	lRatio			: 0.19,
	mainContainer	: "#mySplitter",

	section : {

		toggle : function(sec) {
			var is_open = __k.layout.section[sec].isOpen;
			if(is_open){
				__k.layout.section[sec].close();
			}else{
				__k.layout.section[sec].open();
			}
			return __k.layout.section[sec];
		},

		left : {

			_avatarH : 55,
			_bottomHandleH : 11,
			handle : "#filetree_handle",
			sec_handle : "#filetree_toggle",
			holder : "div#leftPane",
			click_to_start : "img#click_to_start_image",
			isOpen : false,
			open : function() {
				var l = __k.layout;
				if(!l.section.left.isOpen){
					$(l.section.left.sec_handle).css("background-position","right top");
					l.section.left.holder.css("left","-" + l.lpw + "px");
					l.section.left.holder.show();
					l.section.left.click_to_start.hide().remove();
					l.section.left.holder.animate({"left": 0}, __k.layout.duration);
					l.section.right.holder.animate({"width": l.winWidth-l.lpw+"px"},__k.layout.duration,function() {
						l.onResize();
					});
					l.section.left.isOpen = true;
				}
			},
			close : function() {
				var l = __k.layout;
				if(this.isOpen){
					l.section.middle.close();
					l.section.left.holder.animate({"left": "-"+l.lpw+"px"}, __k.layout.duration);
					l.section.right.holder.animate({"width": l.winWidth}, __k.layout.duration,function() {
						$(l.section.left.sec_handle).css("background-position","left top");
						l.onResize();
					});
					l.section.left.isOpen = false;
				}
			}

		},
		right : {
			_tabsH : 0,
			_toolbarH : 33,
			isOpen : true,
			holder : "div#rightPane",
			open : function() {},
			close : function() {}
		},
		middle : {

			tabHeight : 0,
			isOpen : false,
			holder : "div#middlePane",
			open : function() {
				var	l = __k.layout;
				if(!l.section.middle.isOpen){
					var left = (l.section.left.isOpen) ? l.lpw : 0 ;
					l.section.middle.holder.animate({ "left": left+"px"},__k.layout.duration);
					l.section.middle.isOpen = true;
				}
			},
			close : function() {
				var	l = __k.layout;
				if(l.section.middle.isOpen){
					l.section.middle.holder.animate({ "left": "-400px"},__k.layout.duration);
					l.section.middle.isOpen = false;
				}
			}

		},
		top : {

			isOpen : true,
			holder : "div#header_holder",
			height : 40,
			open : function() {},
			close : function() {}
		},
		dash : {

			isOpen : false,
			holder : "div#user_panel",
			handle : "#trigger_fun",
			open : function() {
				var	l = __k.layout;
				if(!l.section.dash.isOpen){
					l.section.dash.holder.animate({ "marginTop": "0px"},__k.layout.duration);
					l.section.dash.isOpen = true;
					$(".trigger_link_toggle").removeClass('trigger_link_active');
					$("#trigger_fun").addClass('trigger_link_active');
					l.section.bottom.close();
				}
			},
			close : function() {
				var	l = __k.layout;
				if(l.section.dash.isOpen){
					l.section.dash.holder.animate({ "marginTop": -1*l.contentHeight},__k.layout.duration);
					l.section.dash.isOpen = false;
					$(".trigger_link_toggle").removeClass('trigger_link_active');
					$("#trigger_work_area").addClass('trigger_link_active');
				}
			}
		},
		bottom : {

			isOpen			: false,
			holder			: "div#bottom_panel",
			handle 			: "#bottom_panel_trigger",
			default_height	: 200,
			height			: 0,
			open : function() {
				var	l = __k.layout;
				if(!l.section.bottom.isOpen){
					l.section.dash.close();
					var h = (l.section.bottom.height !== 0) ? l.section.bottom.height : l.section.bottom.default_height;
					l.section.bottom.holder.animate({ "height": h},__k.layout.duration, function() {
						l.onResize();
						l.section.bottom.holder.find("input#task_logger_command_line").trigger('focus');
						l.section.bottom.holder.find("ul#task_logger").css('max-height',h-55);
					});
					l.section.bottom.handle.animate({"marginTop":"-" + (h+10) + "px"},__k.layout.duration);
					l.section.bottom.isOpen = true;
					l.section.bottom.height = h;
				}
			},
			close	: function() {
				var	l = __k.layout;
				if(l.section.bottom.isOpen){
					l.section.bottom.holder.animate({ "height": 0},__k.layout.duration,function() {
						
					});
					l.section.bottom.handle.animate({"marginTop":"-10px"},__k.layout.duration);
					l.section.bottom.height = 0;
					l.section.bottom.isOpen = false;
					l.onResize();						
				}
			}
		}

	},
	/* !LAYOUT INIT*/
	initialize : function() {
		var that = this;
		$.each(this.section, function(n,v) {
			if(typeof v.holder !== "undefined"){
				that.section[n].holder = $(v.holder);
			}
			if(typeof v.handle !== "undefined"){
				that.section[n].handle = $(v.handle);
				that.section[n].handle.click(function() {
					that.section.toggle(n);
				});
			}
		});
		
		this.section.left.click_to_start = $(this.section.left.click_to_start);
		
		this.section.left.click_to_start.click(function() {
			that.section.left.open();	
		});
		
		this.mainContainer = $(that.mainContainer);
		
		this.winWidth = $(window).width();
		this.winHeight = $(window).height();
		this.lpw = (this.winWidth*0.19 < 260 ) ? 260 : this.winWidth*0.19;
		this.rpw = (this.winWidth*0.19 < 260 ) ? this.winWidth-260 : this.winWidth*0.81;
		this.lRatio = this.lpw / this.winWidth;
		this.onResize();
		
		$("#filetree_toggle").click(function() {
			__k.layout.section.toggle("left");	
		});
		$("#trigger_work_area").click(function() {
			__k.layout.section.dash.close();	
		});

		this.section.left.holder.resizable({
			ghost: false,
			handles: { e : "#filetree_handle"},
			helper: 'ui-state-highlight',
			minWidth: 260,
			stop: function(event, ui) {
				__k.layout.lpw = ui.size.width;
				__k.layout.rpw = __k.layout.winWidth - __k.layout.lpw;
				__k.layout.lRatio = __k.layout.lpw / __k.layout.winWidth;
				__k.layout.onResize(true);
				__k.layout.section.right.holder.unblock();
			},
			start: function(event, ui) {
				__k.layout.section.right.holder.block({
					overlayCSS:  { 
					        backgroundColor: '#000', 
					        opacity:         0.2
					    }				
				});
			}
		});
		
		this.section.bottom.holder.resizable({
			ghost: false,
			/* handles: { n : "#bottom_panel_resizer"}, */
			handles: 'n',
			helper: 'ui-state-highlight',
			minHeight: 50,
			maxHeight: __k.layout.contentHeight,
			resize: function(event, ui) {
				//__k.layout.section.bottom.handle.css("margin-top", "-" + (ui.size.height+10) + "px");			
			},
			stop: function(event, ui) {
				__k.layout.section.bottom.default_height = ui.size.height;
				__k.layout.onResize();
				__k.layout.section.bottom.handle.css("margin-top", "-" + (ui.size.height+10) + "px");
				__k.layout.section.bottom.holder.css("top","auto");
				__k.layout.section.bottom.holder.find("ul#task_logger").css('max-height',ui.size.height-55);
				__k.layout.section.right.holder.unblock();
			},
			start: function(event, ui) {
				__k.layout.section.right.holder.block({
					overlayCSS:  { 
					        backgroundColor: '#000', 
					        opacity:         0.2
					    }				
				});
			}
		});
		
		$(window).bind('resize',function() {
			__k.layout.onResize.call(__k.layout);	
		});
	},

	onResize : function(rf) {
		var obj_control = true;
		$.each(this.section, function(n,v) {
			if(typeof v.holder !== "undefined" && typeof v.holder !== "object"){
				obj_control = false;
			}
		});
		if(!obj_control){
			return false;
		}
		
		this.winWidth = $(window).width();
		this.winHeight = $(window).height();
		this.contentHeight = this.winHeight - this.section.top.height; //- this.section.bottom.height;

		if(rf !== true && this.winWidth*this.lRatio < 260 && this.section.left.isOpen){
			this.lpw = 260;
			this.rpw = this.winWidth-260;
		}else if (rf !== true && this.section.left.isOpen){
			this.lpw = this.winWidth*this.lRatio;
			this.rpw = this.winWidth*(1-this.lRatio);
		}else if (rf !== true && this.section.left.isOpen === false){
			this.rpw = this.winWidth;
		}
		this.lRatio = this.lpw / this.winWidth;
			
		//arrange heights
		this.mainContainer.css({'height' : this.contentHeight});

		//this.section.middle.holder.css({'height' : this.contentHeight});
		this.section.left.holder.css({'height' : this.contentHeight});
		//this.section.right.holder.css({'height' : this.contentHeight});

		this.section.right.holder.find("#kd_tabs").css({'height' : this.contentHeight});
		this.section.right.holder.find(".filetree_shadow").css({'height' : this.contentHeight - this.section.left._avatarH});
		this.section.dash.holder.css({'height' : this.contentHeight, 'margin-top' : -1*this.contentHeight});
		this.section.left.holder.find(".tree_holder").css({'height' : this.contentHeight - this.section.left._avatarH });

		//arrange rest
		this.section.left.holder.css({'width': this.lpw});
		this.section.right.holder.css({'width' : this.rpw});
		
		if (this.section.middle.isOpen){
			this.section.middle.holder.css({'left' : this.lpw});
			__k.quickMenu.resize();
		}
		__ft1.scroll_it();
		//this._stdFrameFix();
		this._bespinSizeFix();
		return this;
	},
	_bespinSizeFix : function() {
		this.section.right.holder.find("div#kd_tabs>div.ui-tabs-panel").css({"width": this.rpw, "height" : this.contentHeight - this.section.right._tabsH}).show();
		this.section.right.holder.find("div#kd_tabs>div.bespin iframe.bespin_container").contents().find("#editor").css({"height" : this.contentHeight - this.section.right._tabsH - this.section.right._toolbarH});
		this.section.right.holder.find("div#kd_tabs>div.ui-tabs-panel .kd_http_container iframe").css({"width": this.rpw, "height" : this.contentHeight - this.section.right._tabsH - this.section.right._toolbarH}).show();
		//if the line below fired when a bespin frame tab inactive
		//it breaks the layout, makes the same effect as -> $('#mySplitter').scrollTop(480);
		//this.section.right.holder.find("div#kd_tabs>div.bespin iframe.bespin_container").contents().find("#editor canvas").focus();
		$('#mySplitter').scrollTop(0);
		$('body').scrollTop(0);
	},
	_stdFrameFix : function() {
		this.section.right.holder.find("div#kd_tabs>div.ui-tabs-panel .kd_http_container iframe").css({"width": this.rpw, "height" : this.contentHeight - this.section.right._tabsH - this.section.right._toolbarH}).show();
		$('#mySplitter').scrollTop(0);
	}

};

/* !FILETREE */
__k.fileTree = {
	
	json		: {},
	memo		: 0,
	options		: {
		files_path		: "/",
		connector_url1	: "/task_ls.php",
		connector_url2	: "/k.php",
		_holder			: ".tree_holder",
		_tree			: "#ftp_filetree",
		_holderHeight	: 0,
		_treeHeight		: 0,
		_item			: "<div class=\"k_filetree_item\"></div>",
		duration		: 200,
		_scrollBar		: "#ft_scroll_bar",
		_scrollBarPosY 	: 0,
		_scrollBarHeight: 0,
		_render_items	: "files,folders",
		_context		: true,
		_selectable 	: true,
		files_event		: "dblclick",
		folders_event	: "dblclick",
		show_hidden_files: false,
		_block_on_load	: true
	},
	scroll_it	: function() {
		//console.log("scroll_it");
		var that = this;
		/*
		if(that.options._scrollBar !== false){
			$(that.options._holder).jScrollPane({
				scrollbarWidth	: 5,
				showArrows		: true,
				wheelSpeed 		: 30,
				animateStep		: 10,
				animateInterval	: 10
			});
			if($(that.options._holder).parent().find('.jScrollPaneDrag').is(':hidden')){
				$(that.options._holder).parent().trigger('mouseenter');
			}
		}
		*/
		if (that.options._scrollBar === false) {return false;}
        that.options._treeHeight = $(that.options._tree).height();
        that.options._holderHeight = $(that.options._holder).height();
		var fw = that.options._treeHeight,
			sw = that.options._holderHeight;
		
		$(that.options._holder).unbind('mousewheel');
		$(that.options._holder).bind('mousewheel', function(event, delta) {
            var dir = delta > 0 ? -1 : 1,
                vel = Math.abs(delta),
            	step = vel*25,
            	actP = $(this).scrollTop(),
            	newP = dir*step+actP;
				
            $(this).scrollTop(newP);

        	actP = $(this).scrollTop();

        	that.options._scrollBarPosY = (actP*sw/fw)+actP;
        	that._showScrollBar(true);
            return false;
	    });
	    that._showScrollBar();
	},
	_showScrollBar : function(scrolling) {
		//console.log("_showScrollBar");
		var that = this;
		if (that.options._scrollBar === false) {return false;}

        that.options._treeHeight = $(that.options._tree).height();
        that.options._holderHeight = $(that.options._holder).height();
		
    	var fw = that.options._treeHeight,
    		sw = that.options._holderHeight,
			$bar = $(that.options._scrollBar);
    	
    	that.options._scrollBarHeight = sw*sw/fw;
		
		/*
		if($bar.hasClass('ui-draggable') !== true){
			$bar.draggable({
				axis		: 'y',
				containment	: 'parent',
				drag: function(event, ui) { 
					//$(that.options._holder).scrollTop();
				},
				stop: function(event, ui) {
				}
			});
		}
		*/

		if(fw>sw){
			$bar.fadeIn(400);
			if(scrolling){
				$bar.css("height" , that.options._scrollBarHeight-7 +"px");
				$bar.css("top" ,  that.options._scrollBarPosY+"px");
			}else{
				$bar.animate({"height" : that.options._scrollBarHeight-7 +"px"},200,function() {
					$bar.css("top" ,  that.options._scrollBarPosY+"px");
				});
			}
		}else{
			$bar.fadeOut(400, function() {
				$(that.options._holder).animate({"scrollTop" : 0},400);
				$bar.css("top" ,  0+"px");
			});
		}
	},
	init_tree 	: function(path,parent,callback) {
		//console.log("init_tree",path);
		var that = this;

		$(document).unbind('.filetree');
		$(document).bind('keydown.filetree', function (evt){
			if (evt.keyCode === 17 || evt.keyCode === 224){
				that._ctrlKey = true;
			}else if(evt.keyCode === 16){
				that._shiftKey = true;
			}
		}).bind('keyup.filetree', function (evt){
			if (evt.keyCode === 17 || evt.keyCode === 224){
				that._ctrlKey = false;
			}else if(evt.keyCode === 16){
				that._shiftKey = false;
			}
		});
		
		
		/* KEYBOARD SUPPORT HACK
		var tid = $(that.options._tree).attr("id");
		if($("#" + tid + "keyboard_hack").length === 0){
			that._keyboard_input_hack = $('<input type="text" class="kodingen_keyboard_hack_input" id="' + tid + 'keyboard_hack" />');
			$("body").append(that._keyboard_input_hack);
		}
		*/
		
		if (typeof parent === "undefined" && typeof path !== "undefined" && path !== "/"){
			path = (path.substr(-1,1) === "/") ? path.substr(-path.length,path.length-1) : path;
			$(that.options._tree).find('.k_filetree_item').each(function() {
				if($(this).data('o').path === path) {
					parent =  $(this);
					if (parent.data('o').type === "files"){
						path = __k.utils.returnParentPath(path) + "/";
						parent =  $(this).parent().prev();
					}else{
						path = path + "/";
						parent =  $(this);
					}
				} 
			});
			
			if (typeof parent === "undefined") {
				that.init_tree(__k.utils.returnParentPath(path));
				return false;
			}else{
				parent.addClass("on_action");
				if(parent.next().hasClass("inner_group")){
					that.collapse_tree(parent);
				}
				that.init_tree(path,parent);
				return false;
			}
		}else if( typeof parent !== "undefined" && parent.next('.inner_group').length === 1 ){ 
			parent.next('.inner_group').slideUp('200', function() {
				$(this).remove();
			});
		}
		
		path = path || this.options.files_path;
		
		var	is_new = false;
		if (path === "/" || ""){
			that.options.show_hidden_files = false;
			is_new = true;
			if(that.options._block_on_load){
				$(that.options._holder).block({ message: '<p class="filetree_loader"></p>' });
			}
			if(that.options._scrollBar !== false){
				$(that.options._holder).scrollTop(0);
			}
		}

		function get_tree_data(path,parent,is_new,callback){
			var taskId = Math.floor(Math.random()*10001);
			__k.utils.taskLogger.print(taskId, "ls -lpFva " + path + "<br/>");
			
			function run_inner_task_listener(path,parent,is_new,callback){
				var params = { "path" : path, "operation" : "ls"};
				$.post(that.options.connector_url2, params, function(json) {
					if(json === null || typeof json !== "object") { 
						__k.utils.console([json,"::problem on filetree response"]);
						return false;
					}else{
						if (typeof json === "object" && typeof json.taskId !== "undefined"){
							__k.utils.task_memo[json.taskId] = {};
							__k.utils.task_memo[json.taskId]["input"] = params;
							__k.utils.task_memo[json.taskId]["command"] = json;
						}
						__k.utils.taskListener(json.taskId, json.cmd, function(r) {
							if(json !== null || typeof json === "object") { 
								//$(parent).data("o","taskId",json.taskId);
								that.render_tree(r.response,parent,is_new);
								if(typeof callback === "function"){
									callback.call(null);
								}
							}
							return delete __k.utils.task_memo[json.taskId];
						});
					}
				},"json");
			}

			if(path.search(/\/private\/Ftps\//) !== -1 ){
				run_inner_task_listener(path,parent,is_new,callback);
			}else{
/*
				if(is_new){
					var r = (__k.user.is_logged_in) ? ["total 1","- - - - - 2010-Feb-07 20:16 " + __k.user.data.user_login + ".kodingen.com\/"] : ["total 22","- - - - - 2010-Jan-25 16:45 guest.kodingen.com\/","- - - - - 2010-Mar-04 08:52 img_Daffodil_Days_1600.jpg","- - - - - 2010-Mar-04 08:52 img_Fish_1600.jpg","- - - - - 2010-Mar-04 08:52 img_Gran_Paradiso_1600.jpg","- - - - - 2010-Mar-04 08:53 img_Lightning_1600.jpg","- - - - - 2010-Mar-04 08:53 img_One_Drop_1600.jpg","- - - - - 2010-Mar-04 08:53 img_South_Pacific_1600.jpg","- - - - - 2010-Mar-04 08:53 img_Yellow_1600.jpg","- - - - - 2010-Mar-04 08:53 test.asp","- - - - - 2010-Mar-04 08:53 test.cfm","- - - - - 2010-Mar-04 08:53 test.cgi.html","- - - - - 2010-Mar-04 08:53 test.fcgi","- - - - - 2010-Mar-04 08:53 test.fcgi.py","- - - - - 2010-Mar-04 08:53 test.html","- - - - - 2010-Mar-04 08:53 test.js","- - - - - 2010-Mar-04 08:53 test.json","- - - - - 2010-Mar-04 08:53 test.mvc","- - - - - 2010-Mar-04 08:53 test.php","- - - - - 2010-Mar-04 08:53 test.pl","- - - - - 2010-Mar-04 08:53 test.py","- - - - - 2010-Mar-04 08:53 test.shtml","- - - - - 2010-Mar-04 08:53 test.style.css"];
					that.render_tree(r,parent,is_new);
					if ($.isArray(r)){
						$.each(r, function(i,t) {
							__k.utils.taskLogger.print(taskId,t + "<br/>");
						});
					}else{
						__k.utils.taskLogger.print(taskId,r + "<br/>");
					}
					if(typeof callback === "function"){
						callback.call(null);
					}
				}else{
*/
					$.get(that.options.connector_url1, { "path" : path }, function(r,s) {
						if (s === "success" && r.status !== '-404'){
							that.render_tree(r,parent,is_new);
							if ($.isArray(r)){
								$.each(r, function(i,t) {
									__k.utils.taskLogger.print(taskId,t + "<br/>");
								});
							}else{
								__k.utils.taskLogger.print(taskId,r + "<br/>");
							}
							if(typeof callback === "function"){
								callback.call(null);
							}
						}else{
							run_inner_task_listener(path,parent,is_new,callback);
						}
					},"json");
/* 				} */
			}
		}
		
		get_tree_data(path,parent,is_new,callback);
		
	},
	render_tree	: function(json,parent,is_new) {
		//console.log("render_tree");
		var that = this,
			$root = $(that.options._tree),
			items = [],
			count = 0,
			$parent = parent || $root,
			sanitize = sanitize || true,
			parent_id = $parent.attr("id");
		
		json = that.sanitizeJson(json,$parent);
		
		that._ctrlKey = false;
		that._shiftKey = false;
		//__k.utils.console([json]);
		if(is_new) { 
			$(that.options._tree).html("");
			that.scroll_it(); 
		}

		//loop all entities
		$.each(json, function(j,val) {
			if (that.options._render_items.search(j) !== -1) {
				//get types and render them [files,folders,etc]
				$.each(val, function(i,v) {
					var $item = $(that.options._item);
					var hidden = (v.hidden) ? "none hidden_file" : "";
					v.type = j;
					$item.attr("id","item_"+that.memo).addClass(j).addClass(hidden).html(v.name).data("o",v);
					items[count] = $item;
					that.bind_event($item);
					count++;
					that.memo++;
				});
			}
		});
		
		that.expand_tree($parent,items,is_new);
			
	},
	sanitizeJson : function(json,parent) {
		//console.log("sanitizeJson");
		/*
        "filename59": {
            "name": "filename59",
            "size": 33,
            "type": 0,
            "perms": 14,
            "owner": 97,
            "path": 65
        }*/

		var that = this;
		var newJson = {
			"folders"	: {},
			"files"		: {}

		};
		
		if (typeof json === "undefined") {
			//console.log(false);
			return false;	
		}else{

			json.shift();
			$.each(json, function(i,t) {
				//hide invalid filetree items
				var tmp = t.split(' ');
				if (t.search(/:/) !== -1 && tmp[tmp.length-1] !== './' && tmp[tmp.length-1] !== '../'){
	
					//get the filename.
					var tx = t.split(":")[1];
					var parentPath = "";
					
					tx = tx.substring(3);
					var filename = tx.split(" -> ")[0];
						
					var typeIndicator,ti = t.substring(t.length-1,t.length);
					
					var type = (ti==="/") ? "folders" : "files";
								
					// remove double spaces
					while(t.search(/  /) !== -1){ 
						t = t.replace(/  /g, " ");
					}
					
					var tP = t.split(" ");
					
					$.each(tP,function(k,v){	
						if(v==="") { tP.splice(k);}
					});
						
					if( ti === "@" || ti === "/" || ti === "|" || ti === "*" || ti === ">" || ti === "=" ){ 
						var f_minus_one = filename.substring(0,filename.length-1);
						var f_last_char = filename.substring(filename.length-1);
						filename 	= f_last_char === ti ? f_minus_one : filename;
					}
					
					if(typeof parent.data("o") !== "undefined"){ 
						parentPath = parent.data("o").path;
					}
					
					newJson[type][filename] = {};
					newJson[type][filename]["name"]  = filename;
					newJson[type][filename]["perms"] = tP[0];
					newJson[type][filename]["owner"] = tP[2];
					newJson[type][filename]["group"] = tP[3];
					newJson[type][filename]["path"]  = parentPath + "/" + filename;
					newJson[type][filename]["abs_path"]  = parentPath + "/" + filename;
					newJson[type][filename]["type"]  = type;
					newJson[type][filename]["date"]  = tP[5] + " " + tP[6];
	
					var hidden = false;
					var path = parentPath + "/" + filename;
					var domain_path = "/" + __k.user.data.plesk.domain_data[0].domain_name;
					
					if( path.search( domain_path + "/anon_ftp") !== -1 ||
						path.search( domain_path + "/conf") !== -1 ||
						path.search( domain_path + "/cgi-bin") !== -1 ||
						path.search( domain_path + "/statistics") !== -1 ||
						path.search( domain_path + "/pd") !== -1 ||
						path.search( domain_path + "/web_users") !== -1 ||
						path.search( domain_path + "/httpdocs/plesk-stat") !== -1 ||
						path.search( domain_path + "/httpsdocs/plesk-stat") !== -1 ||
						path.search( domain_path + "/bin") !== -1 ||
						path.search( domain_path + "/error_docs") !== -1 ||
						path.search( domain_path + "/subdomains/kodingen-bridge") !== -1 ||
						path.search( domain_path + "/httpsdocs") !== -1
					){
						hidden = (that.options.show_hidden_files === false) ? true : false;
					}
					newJson[type][filename]["hidden"]  = hidden;
				}			
			});
		
		}
		return newJson;	
	},
	show_hidden_files : function(state) {
		var that = this;
		if (state) {
			$(that.options._tree).find('div.k_filetree_item.none').slideDown(400,function() {
				that.scroll_it();
			});
			that.options.show_hidden_files = true;
		}else{
			$(that.options._tree).find('div.k_filetree_item.none').slideUp(400,function() {
				that.scroll_it();
			});
			that.options.show_hidden_files = false;
		}
	},
	collapse_tree : function($item) {
		//console.log("collapse_tree");
		var that = this;
		that._ui_select(that._selected_item);
		$item.next().slideUp(that.options.duration,function() {
			$(this).remove();
			that.scroll_it();
			$item.removeClass("expanded");
			that._ui_select(that._selected_item);
		});
	},
	expand_tree : function($parent,items,is_new) {
		//console.log("expand_tree");
		var that = this,
			pl = 0,
			parent_id = $parent.attr("id");

		//if(!is_new && $parent.next('.inner_group').length === 0){
		if(!is_new){
			$parent.after("<div parent_id="+parent_id+" class=\"inner_group none\"></div>");
			pl = parseInt($parent.children('span.icon').css("margin-left"),10);
		}
		
		$.each(items, function(j,val) {
			var ext = (val.data("o").type === "files") ? __k.utils.returnExtension(val.data("o").name) : "",
				$icon = $('<span class="icon '+ext+'"></span>');

			if(is_new){
				$parent.append(val);
			}else{
				$parent.next().append(val);
			}
			if(that.options._context){
				$icon.bind('click', function(event) {
					event.stopPropagation();
					that._ui_select(val);
					__k.contextMenu._create(val,event);
				});
			}
			val.prepend($icon);
		});
		var ca = $parent.next().children().children().length;
		ca = (ca > 10) ? 10 : ca;
		$parent.next().children().children().css("margin-left",(pl+10) +"px");
		//that._ui_select(that._selected_item);
		$parent.next().slideDown(50*ca, function() {
			$parent.removeClass("on_action");
			that.scroll_it();
			$parent.addClass("expanded");
	        that.options._treeHeight = $(that.options._tree).height();
	        that.options._holderHeight = $(that.options._holder).height();
		});
		
		if(that.options._block_on_load	=== true){
			$(that.options._holder).unblock();
		}
	},
	bind_event	: function($item) {
		//console.log("bind_event");
		var that = this,
			o = $item.data("o");
		
		$item.bind(that.options[ o.type + "_event"], function(event) {
			event.stopPropagation();
			event.preventDefault();
			switch (o.type) {
				case "files" :
					__k.utils.sendFileToEditor(o.path,o.title);
				break;
				case "folders" :
					if (that.options._selectable) {
					}
					if ($item.hasClass("on_action")) {return false;}
					//expand/collapse folder
					if($item.next().hasClass("inner_group")){
						that.collapse_tree($item);
					}else{
						that.init_tree(o.path + "/",$item);
						$item.addClass("on_action");
					}
				break;
			}
			that._ui_select($item);
		}).bind('click',function(event) {
			event.stopPropagation();
			that._ui_select($item);
		});

		if(that.options._context){
			$item.rightClick(function(event) {
				event.stopPropagation();
				event.preventDefault();
				that._ui_select($item);
				__k.contextMenu._create($item,event);
				return false;
			});
		}
		
	},
	_ui_select : function($item) {
		//console.log("_ui_select");
		var that = this;
		if ($item === false) {return false;}

		/* FOR MULTIPLE SELECTION
		if(!that._ctrlKey){
			$(that.options._tree).find('.selected').removeClass('selected');
		}
		
		if(that._shiftKey){
			var $otherItem = $(that.options._tree).find('div.k_filetree_item.selected').eq(0);
			var i = $(that.options._tree).find("div.k_filetree_item").index($otherItem);
			var j = $(that.options._tree).find("div.k_filetree_item").index($item);
			
			$(that.options._tree).find('.selected').removeClass('selected');
			$(that.options._tree).find("div.k_filetree_item").eq(i).addClass('selected');
			$(that.options._tree).find("div.k_filetree_item").eq(j).addClass('selected');
			while(i !== j){
			    $(that.options._tree).find("div.k_filetree_item").eq(i).addClass('selected');
			    if (i>j){i--}else{i++}
			}
		}
		*/
		$(that.options._tree).find('.selected span.nav_icon').remove();
		$(that.options._tree).find('.selected').removeClass('selected');
		$item.addClass('selected');
		var $input = $(that._keyboard_input_hack).focus();
		that._keyboard_support($input);
		that._selected_item = $item;
		that._navigation_put($item)
		
		//that._get_next_item($item);
		//that._get_prev_item($item);
		
	},
	_navigation_menus : {
		trash 		: {
			"location"	: "/private/Trash",
			"menu"		: "<ul alt='trash'><li operation='emptyTrash'><span class='icon emptyTrash'></span>Empty Trash</li></ul>",
			emptyTrash	: function($item,o) {
				var params = {"operation":"empty_trash"};
				__k.utils.save_prefs("",params,function() {
					__ft1.init_tree(o.path);
				});
			}
		},
		http			: {
			"location"	: "/httpdocs",
			"menu"		: "<ul alt='http'><li operation='http'><span class='icon http'></span>Visit page</li></ul>",
			http		: function($item,o) {
				var self = this._navigation_menus.http,
					folder = o.path;
				
				folder = folder.replace(/\/httpdocs/,"");
				var domain_path = __k.user.data.plesk.domain_data[0].domain_name;
				
				if ( folder.search(domain_path + "\/subdomains") !== -1 ){
					folder = folder.replace(domain_path + "\/subdomains","");
					folder = folder.replace(/\/\//ig,"/");
					var ff = folder.split("/");
					ff.shift();
					folder = ff.shift() + "." + domain_path.replace(/\//,"") + "/" + ff.join("/");
				}
				if(folder[0] === "/"){folder = folder.substr(1,folder.length-1);};
				__k.utils.sendFileToEditor(folder + ".httpwebserver", o.name)
			}
		},
		https			: {
			"location"	: "/httpsdocs",
			"menu"		: "<ul alt='https'><li operation='https'><span class='icon http'></span>Visit page</li></ul>",
			https		: function($item,o) {
				var self = this._navigation_menus.https,
					folder = o.path;
				folder = folder.replace(/\/httpsdocs/,"");
				var domain_path = __k.user.data.plesk.domain_data[0].domain_name;
				
				if ( folder.search(domain_path + "\/subdomains") !== -1 ){
					folder = folder.replace(domain_path + "\/subdomains","");
					folder = folder.replace(/\/\//ig,"/");
					var ff = folder.split("/");
					ff.shift();
					folder = ff.shift() + "." + domain_path.replace(/\//,"") + "/" + ff.join("/");
				}
				if(folder[0] === "/"){folder = folder.substr(1,folder.length-1);};
				__k.utils.sendFileToEditor(folder + ".httpwebserver", o.name)
			}
		},
		ftps			: {
			"location"	: "/private/Ftps/",
			"menu"		: "<ul alt='ftps'><li operation='remountFtp'><span class='icon ftpRemount'></span>Remount FTP</li></ul>",
			remountFtp	: function($item,o) {
				var params = {"operation":"remount_ftp","name":o.name,"path":o.path};
				__k.utils.save_prefs("",params,function() {
					__ft1.init_tree(o.path);
				});
			}
		}/*
,
		subdomains		: {
			"location"	: "/subdomains/",
			"menu"		: "<ul alt='subdomains'><li operation='http'><span class='icon http'></span>Visit page</li></ul>",
			http		: function($item,o) {
				var self = this._navigation_menus.subdomains,
					folder = o.path;
				
				console.log(__k.user, o);
				folder = folder.replace(,"");
				__k.utils.sendFileToEditor(folder + ".httpwebserver", o.name)
			}
		}
*/
	},
	_navigation_put : function($item) {
		var that = this,
			o = $item.data("o"),
			menu = "";
		if(typeof $item.data("o") !== "object"){return false;}
		
		$.each(that._navigation_menus, function(i,t) {
			if (o.abs_path.search(t.location) !== -1){
				menu = t.menu;
			}
		});

		$("body").find('.nav_icon_context_menu').remove();
		
		if(menu !== ""){
			var $nav_trigger = $('<span class="nav_icon"></span>');
			var $nav_menu = $('<div class="context_menu nav_icon_context_menu none"></div>');
			
			$nav_menu.append(menu);
			$("body").append($nav_menu);
			$item.append($nav_trigger);
			
			var nav_trigger_timer = false;
			var nav_menu_timer = false;
			$nav_trigger.bind('mouseenter',function(e) {
				nav_trigger_timer = setTimeout(function() {
					$nav_menu.css({"top":$nav_trigger.offset().top + 15, "left":$nav_trigger.offset().left}).fadeIn(400);
					nav_menu_timer = setTimeout(function() {
						$nav_menu.trigger('mouseleave');	
					},2000)	
				},500);
			}).bind('mouseleave',function(e) {
				clearTimeout(nav_trigger_timer);
			});

			$nav_menu.bind('mouseleave',function() {
				nav_menu_timer = setTimeout(function() {
					$nav_menu.fadeOut(400);
				},500);
			}).bind('mouseenter',function(e) {
				clearTimeout(nav_menu_timer);
			});
			
			$nav_menu.find('li').bind('click',function() {
				var operation = $(this).attr('operation'),
					menu = $(this).parent().attr('alt');
					
				that._navigation_menus[menu][operation].call(that,$item,o);
			});
		}
	},	
	_keyboard_input_hack : {},
	_is_keyboard_support_set : false,
	_gi_counter : 0,
	_get_next_item : function($item) {
		if($item.next().hasClass("k_filetree_item")){
			this._next_item = $item.next();
		}else if ($item.next().hasClass("inner_group")){
			this._next_item = $item.next().find(".k_filetree_item").eq(0);
		}else if ($item.next().length === 0){
			//this._next_item = $(this.options._tree).find('.inner_group:first').next();
			this._get_next_item($item.parent());
		}
	},
	_get_prev_item : function($item) {
		if($item.prev().hasClass("k_filetree_item")){
			this._prev_item = $item.prev();
		}else if ($item.prev().hasClass("inner_group")){
			this._prev_item = $item.prev().find(".k_filetree_item:last");
		}else if ($item.prev().length === 0){
			//this._prev_item = $(this.options._tree).find('.inner_group:last').prev();
			this._get_prev_item($item.parent());
		}
	},
	_selected_item : false,
	_next_item : false,
	_prev_item : false,
	_keyboard_support : function($input) {
		var that = this;
		/*
		if(this._is_keyboard_support_set){
			$input.unbind('keydown', 'up');
			$input.unbind('keydown', 'right');
			$input.unbind('keydown', 'down');
			$input.unbind('keydown', 'left');
		}
		
		$input.bind('keydown', 'up', function (evt){
			
			var ih = that._selected_item.outerHeight(),
				six = $(that.options._tree).find('.k_filetree_item').index(that._selected_item)+1,
				si_bottom = six * ih,
				ti = $(that.options._tree).find('.k_filetree_item').length;
				
			if (si_bottom-ih < $(that.options._holder).scrollTop()) {
				$(that.options._holder).scrollTop(si_bottom-ih);
				that._showScrollBar();
			}
			that._ui_select(that._prev_item);
		})
		$input.bind('keydown', 'right', function (evt){
			var o = that._selected_item.data("o");
			if(o.type === "folders" && that._selected_item.hasClass('expanded') === false)
			that._selected_item.trigger('dblclick');
		})
		$input.bind('keydown', 'down', function (evt){
			that._ui_select(that._next_item);
			var ih = that._selected_item.outerHeight(),
				six = $(that.options._tree).find('.k_filetree_item').index(that._selected_item)+1,
				si_bottom = six * ih,
				ti = $(that.options._tree).find('.k_filetree_item').length;
				
			if (si_bottom > that.options._holderHeight) {
				
				$(that.options._holder).scrollTop(si_bottom - that.options._holderHeight);
				that._showScrollBar();
		
			}
		})
		$input.bind('keydown', 'left', function (evt){
			var o = that._selected_item.data("o");
			if(o.type === "folders" && that._selected_item.hasClass('expanded')){
				that._selected_item.trigger('dblclick');
			}else{
				that._selected_item.closest('.inner_group').prev().trigger('click');
			}
		})
		
		this._is_keyboard_support_set = true;
		
		*/
	},
	_reset : function() {
		this._selected_item = false;
		this._next_item = false;
		this._prev_item = false;
		this._gi_counter = 0;
		this.memo = 0;
		this.init_tree();
		var $input = $(this._keyboard_input_hack).blur();

		/*
		$input.unbind('keydown', 'up');
		$input.unbind('keydown', 'right');
		$input.unbind('keydown', 'down');
		$input.unbind('keydown', 'left');
		*/
		
	}
};

/* !CONTEXTMENU */
__k.contextMenu = {
	
	_modal_url	: "/kodingen/kd_includes/_modals/modal.context.fs.php",
	_body 		: "#container_editor",
	_holder 	: "<div class='context_menu'></div>",
	_modal_box	: "#kodingen_modal_box",
	_prevMenu	: "temp",
	_create 	: function($item,event) {
		var that = this,
			$menu = $(that._holder),
			o = $item.data("o"),
			ext = __k.utils.returnExtension(o.path);
			
		//create menu
		switch (o.type) {
			
			case "files" :
				//common operations, [appended to files and folders]
				$menu.append("<ul>"+that.templates.common_actions.html+"</ul>");
				$menu.append("<ul>"+that.templates.file_actions.html+"</ul>");
				var editor = false;
				$.each(__k.utils.context_extensions, function(name,val) {
					$.each(val, function(i,v) {
						if (v === ext) {
							editor = (name === "own") ? v : name;
						}
					});
				});
				if (editor !== false && typeof that.templates.ext_actions[editor] !== "undefined" ) {
					$menu.append("<ul>"+that.templates.ext_actions[editor]+"</ul>");
				}
			break;
			case "folders" :
				//common operations, [appended to files and folders]
				$menu.append("<ul>"+that.templates.common_actions.html+"</ul>");
				$menu.append("<ul>"+that.templates.folder_actions.html+"</ul>");
			break;
			case "tree_holder" :
				//clicking to empty tree
			break;
			default:
			return false;
		}

		//common operations, [appended on all context instances]
		$menu.append("<ul>"+that.templates.common_operations.html+"</ul>");
		if (typeof that._prevMenu !== "string") {that._close(that._prevMenu,true);}
		
		//position menu
		$menu.css({ top: that._yPos.call($menu, event.pageY) - 10 , left: event.pageX - 10 });

		//loop through all menu items
		$menu.find('li').each(function() {
			var $node = $(this),
				action = $(this).attr('id'),
				operation = $(this).attr('operation'),
				self = this;
			//bind events for the looped item
			$node.noContext();
			$node.bind('click.context',function(event) {
				event.stopPropagation();
				event.preventDefault();
				that._close($menu);
				o.operation = operation;
				switch (operation) {
				
					case "open" :
						if (o.type === "files"){
							window.__k.utils.sendFileToEditor.call(__k,o.path,o.name);
						}else{
							$item.trigger(__ft1.options.folders_event);
						}
					break;
					case "reload" :
						window.__ft1.init_tree.call(__ft1);
					break;
					case "toggle_hidden" :
						var state = (__ft1.options.show_hidden_files) ? false : true; 
						__ft1.show_hidden_files(state);
					break;
					case "upload" :
						__k.quickMenu.loadData(__k.base.quickMenu.uploader + '?path=' + o.path);
					break;
					case "copy" :
						__k.contextMenu.actions.copy_move(o);
					break;
					case "move" :
						__k.contextMenu.actions.copy_move(o);
					break;
					case "new_file" :
						o.path = (o.type === "files") ? __k.utils.returnParentPath(o.path) : o.path;
						__k.quickMenu.loadData(__k.base.ajaxUrl.cm_path + o.operation + ".php", o);
					break;
					case "download" :
						var params = {"operation" : "publish_path_to_url", "path" : o.path};
						__k.utils.save_prefs(__k.base.ajaxUrl.def,	params);
					break;
					case "zip_download" :
					/*
					o.path = (o.type === "files") ? __k.utils.returnParentPath(o.path) : o.path;
					var params = {"operation" : "publish_path_to_url", "path" : o.path};
					__k.utils.save_prefs(__k.base.ajaxUrl.def,	params, function(r,s){
						if(r !== null || typeof r === "object") { 
							var file_location = r.response[1];
							o.download_path = file_location;
							__k.quickMenu.loadData(__k.base.ajaxUrl.cm_path + "zip_download.php", o);
						}
					});
					*/
					break;
					case "open_with" :
						var ext = __k.utils.returnExtension(o.name);
						__k.user.reset_ui_state(ext);
						window.__k.utils.sendFileToEditor.call(__k,o.path,o.name);
					break;
					case "new_folder" :
						o.path = (o.type === "files") ? __k.utils.returnParentPath(o.path) : o.path;
						__k.quickMenu.loadData(__k.base.ajaxUrl.cm_path + o.operation + ".php", o);
					break;
					default :
						__k.quickMenu.loadData(__k.base.ajaxUrl.cm_path + o.operation + ".php", o);
					break;
				}
			});
		});

		//put ready menu in document body
		$("body").append($menu);
		//memoize this menu for next use
		that._prevMenu = $menu;
		//bind mouse events to menu itself
		var t;
		$menu.mouseleave(function() {
			t = setTimeout(function() {
				that._close($menu);
			},400);
		}).mouseenter(function() {
			clearTimeout(t);
		});
		
		
		
		
	},
	_yPos : function(y) {
		var mh = $(this).find('li').length * 22 + $(this).find('ul').length * 11,
			wh = __k.layout.winHeight;

		y = ( mh + y > wh ) ? y-(mh+y-wh) : y ;
		if ( y < 0 ) {
			$(this).height(wh).css('overflow','auto');
			y = 0;
		}
		return y;
	},
	_close : function($menu,immediate) {
		immediate = immediate || false;
		if (!immediate) {
			$menu.fadeOut(200,function() {
				//first unbind events of menu items, then remove menu itself
				$menu.find('li').unbind('click.context').end().remove();
			});
		}else{
			$menu.find('li').unbind('click.context').end().remove();
		}
	},
	_destroy : function() {
		$('.contextMenu li').unbind('click.context').end().remove();
		$('.contextMenu').remove();
	},
	openModal : function(path,operation,cssclass) {
	    $(__k.contextMenu._body).block({message: false, showOverlay: false});
	   	$.ajax({
		   type: "POST",
		   url: __k.contextMenu._modal_url,
		   cache: false,
		   data: { path : path, operation : operation, cssclass : cssclass},
		   success: function(data){
		     $(__k.contextMenu._modal_box).html(data).show();
		   }
		});	
	},
	templates : {
	
		separator 		: "<hr/>",
		common_actions 	: {
			html 	: 	'<li id="ft_cm_open" 			operation="open"><span class="icon open"></span>Open</li>'+
						'<li id="ft_cm_rename" 			operation="rename"><span class="icon renameFile"></span>Rename...</li>'+
						'<li id="ft_cm_copy" 			operation="copy"><span class="icon copyFile"></span>Copy to...</li>'+
						'<li id="ft_cm_move" 			operation="move"><span class="icon moveFile"></span>Move to...</li>'+						
						'<li id="ft_cm_setPermissions"	operation="chmod"><span class="icon setPermissionsFile"></span>Set Permissions...</li>'+
						'<li id="ft_cm_compress" 		operation="compress"><span class="icon zipFile"></span>Compress</li>'
		},
		common_operations: {
			html 	: 	'<li id="ft_cm_newFile" 		operation="new_file"><span class="icon newFile"></span>New File</li>'+
				    	'<li id="ft_cm_newFolder"		operation="new_folder"><span class="icon newFolder"></span>New Folder</li>'+
				    	'<li id="ft_cm_upload" 			operation="upload"><span class="icon uploadFile"></span>Upload File(s)</li>'+
				    	'<li id="ft_cm_newExternal" 	operation="download_url"><span class="icon newExternal"></span>Download from Internet</li>'+
				    	'<li id="ft_cm_togglehidden" 	operation="toggle_hidden"><span class="icon copyFile"></span>Toggle System files</li>'+
						'<li id="ft_cm_refresh" 		operation="reload"><span class="icon refreshFileTree"></span>Refresh Filetree</li>'
		},
		file_actions	: {
			html 	: 	'<li id="ft_cm_open_with" 		operation="open_with"><span class="icon open_with"></span>Open with...</li>'+
						'<li id="ft_cm_downloadFile"	operation="download"><span class="icon downloadFolder"></span>Download</li>'+
						'<li id="ft_cm_zipDownloadFile" operation="zip_download" class="none"><span class="icon downloadFolder"></span>Zip&amp;Download</li>'+
						'<li id="ft_cm_delete" 			operation="delete_file"><span class="icon deleteFile"></span>Delete</li>'
		},
		folder_actions	: {
			html 	: 	'<li id="ft_cm_downloadFolder" 	operation="zip_download"><span class="icon downloadFolder"></span>Zip&amp;Download</li>'+
						'<li id="ft_cm_delete" 			operation="delete_folder"><span class="icon deleteFile"></span>Delete</li>'
		},
		ext_actions	: {
			extract		: '<li id="ft_cm_extract"			operation="extract"><span class="icon unzipFile"></span>Extract to...</li>'
		}
	
	},
	actions : {
	
		open : function(o) {},
		rename : function(o) {},
		copy_move : function(o) {
			var $tree = $(__k.fileTree.options._tree);
			$tree.block({
				overlayCSS:{
					opacity: "0.3"
				} 
			});
			__k.quickMenu.loadData(__k.base.ajaxUrl.cm_path + o.operation + ".php", o, function() {
				var t = setTimeout(function() {
					try{
						var $tree2 = $(__ft2.options._tree);
						__ft2.init_tree("/",$tree2,function() {
							$tree2.find("div.k_filetree_item").die('mousedown');
							$tree2.find("div.k_filetree_item").live('mousedown', function() {
								var o = $(this).data("o");
								$("input#ft_qm_target").val(o.path);
							});
							
							$tree2.closest(".screen").find("span.back_button").die('click');
							$tree2.closest(".screen").find("span.back_button").live('click', function() {
								$(__ft1.options._tree).unblock();
							});
						});
					}catch(err){
						console.log(err);
					}
				},1000);
			});
			
		}	
	}


};
/* !DASHBOARD */
__k.dashboard = {
	
	options : {
		widget_selector			: ".default_widget",
		widget_store_selector	: "#widget_store",
		widget_store			: false,
		widget_store_url		: false,
		widget_wrapper			: "<div class='fl default_widget' style='left: 30px; top: 30px; position:absolute'>"+
	  								"<div class='default_widget_content'>"+
										"<div id='infoButton'></div>"+
									"</div>"+
								  "</div>",
		widget_json				: [
			{ 
				"name" 					: "sticky",
				"store_icon"			: "/kodingen/widget_store/sticky_thumb.png",
				"widget_settings_html"	: "",
				"widget_front_html"		: '<div id="up_sticky" class="sticky_note">'+
												'<textarea></textarea>'+
										  '</div>'
			},
			{ 
				"name" 					: "last.fm",
				"store_icon"			: "/kodingen/widget_store/lastfm_thumb.png",
				"widget_settings_html"	: "",
				"widget_front_html"		: ""
			}
		]
	},

	init : function() {
		var that = this;
		that.options.widget_store = $(that.options.widget_store_selector);
		
		that.oldStuff();
	},
	create_store : function() {
		
	},
	bind_events : function($widget){
	
	},
	init_user_widgets : function() {
		
	},
	oldStuff : function() {
		
		$(".default_widget").draggable({
			stack: { group: '.default_widget', min: 50 },
			cancel: '.default_widget_content, object, embed'
		});
		
		$("#user_panel_widgets_handle").toggle(function(){
			$(".user_panel_widgets_bar").animate({"height": 100, "opacity": 0.9, "padding": 10}, 200);
			$(this).animate({"marginTop": 130}, 400);
			$(this).css("background-position","top left");
		},function(){
			$(".user_panel_widgets_bar").animate({"height": 0, "opacity": 0, "padding": 0}, 200);
			$(this).animate({"marginTop": 10}, 400);
			$(this).css("background-position","bottom left");
		});
	}
	

}



/* !TABS */
__k.tabs = {
	container :	"",
	currentTabId : "",
	currentTabPanelId : "",
	create : function(container) {
		var that = this;
		that.container = container;
	   	var $kdTabs = $(container).tabs({
		    //to lock the tab content links in the tab
		    load: function(event, ui) {
		        $('a', ui.panel).click(function() {
		            $(ui.panel).load(this.href);
		            return false;
		        });
		    },
		    add: function(event, ui) {
		    	that.currentTabPanelId = ui.panel.id;
	
		    	$(ui.tab).append("<div class='kd_tab_close' title='Close t-ab'> </div>");
		    	
		    	$kdTabs.tabs('select', ui.index);
				
				$(ui.tab).find(".kd_tab_close").bind('click.closeTab', function(){
					$("#kd_tabs").tabs( 'remove' , ui.index );
				});
			    
			    $("#more_videos_strip .video_thumb_active").trigger("click");
				var t = setTimeout(function(){
					$("ul.ui-tabs-nav, #kd_tabs_arrow_clear").animate({"height":"show"}, 400, function(){
						__k.layout.section.right._tabsH = 22;
						__k.layout.onResize();
						var tt = setTimeout(function(){
							$("#kd_community_tab_selector").parent('li').animate({'width':'39px'}, 400, function(){
								$("#kd_community_tab_selector").find('span').html('.');
							});
						},2000);
					});
				},1000);
			    that.tabsSlider();
		    },
		    select: function(event, ui) {
			    that.currentTabPanelId = ui.panel.id;   // element, that contains the selected/clicked tab contents
			},
			show: function(event, ui) {
			    that.currentTabPanelId = ui.panel.id;   // element, that contains the selected/clicked tab contents
			},
			remove: function(event, ui) {
				$(".kd_tab_close").unbind('click.closeTab');
				$("#welcome_kd_tab_close").unbind('click');
				$("#kd_tabs ul.ui-tabs-nav li a").each(function(i){
					$(".kd_tab_close").eq(i).bind('click.closeTab', function(event){
						$("#kd_tabs").tabs( 'remove' , i );
					});	    	
				});
				
				if( $kdTabs.tabs('length') == 1 ){
					var t = setTimeout(function(){
						$("ul.ui-tabs-nav, #kd_tabs_arrow_clear").animate({"height":"hide"}, 400, function(){
							__k.layout.section.right._tabsH = 0;
							__k.layout.onResize();
						});
					},1000);
				}
			    that.tabsSlider();
			}		
		});

		$kdTabs.tabs('select',0);
		that.sortable();
	},
	tabsSlider : function() {
		var that = this,
			$container = $(that.container);

		//unbind events on recall
		$container.find("#kd_tabs_arrow_right, #kd_tabs_arrow_left").unbind(".slideTab");
		var tabsTotalWidth = 0;
		
		//calculate tab's total width by sum of each tab's width
		$container.find('ul.ui-tabs-nav li').each(function(i){
		    tabsTotalWidth += $(this).outerWidth();
		});
	
		//check if we should place sliders or not
		if(tabsTotalWidth > __k.layout.rpw){
		
		//show slider arrows
		$container.find("#kd_tabs_arrow_right, #kd_tabs_arrow_left").show(400);
		//put margins to tabs holder, as large as sliders are
		$container.find("ul.ui-tabs-nav").animate({"marginLeft":"22px", "marginRight":"22px"},400);
		
		//calculate the pixels that are outside of viewport, initially left side is 0...
		//i used '__k.layout.rpw' which is my global var for keeping content width
		//and substracted margins of tabs holder
		var tabAreaWidth = __k.layout.rpw-44;
		var toRight = tabsTotalWidth-tabAreaWidth;
		var toLeft = 0;
		
		//bind events
		//tab holder should slide to 2px per milisecond
		$container.find("#kd_tabs_arrow_left").bind("mouseenter.slideTab", function(event){
			$container.find("ul.ui-tabs-nav").animate({"marginLeft": "+="+toLeft+"px"}, toLeft/2, "easeOutQuad");
		});
		$container.find("#kd_tabs_arrow_right").bind("mouseenter.slideTab",function(event){
			$container.find("ul.ui-tabs-nav").animate({"marginLeft": "-="+toRight+"px"}, toRight/2, "easeOutQuad");
		});
		//on mouseleave re-calculate with margins in mind
		$container.find("#kd_tabs_arrow_right, #kd_tabs_arrow_left").bind("mouseleave.slideTab", function(event){
			$container.find("ul.ui-tabs-nav").stop();
			l = $container.find("ul.ui-tabs-nav").css("margin-left");
			toLeft = Math.abs(parseInt(l,10)-22);
			toRight = tabsTotalWidth-tabAreaWidth-toLeft;
		});
		//make tab holder slide to the newly shown tab in first second
		//and in the other second perform a mouseleave to make the slider arrows ready again
		var t = setTimeout(function(){
			$container.find("#kd_tabs_arrow_right").trigger("mouseenter.slideTab");
			var tt = setTimeout(function(){
				$container.find("#kd_tabs_arrow_right").trigger("mouseleave.slideTab");
			},1000);
		},1000);
		
		}else{
			//if we have enough space and do not need slider arrows
			//if arrows are there hide them and revert the margins of tab holder
			$container.find("#kd_tabs_arrow_right, #kd_tabs_arrow_left").hide(400);
			$container.find("ul.ui-tabs-nav").animate({"marginLeft": "0px"}, 400);
		}		
	},
	sortable : function() {
		var that = this,
			$container = $(that.container);
			
		$container.find(".ui-tabs-nav").sortable({
			axis:'x', 
			accurateIntersection: true, 
			delay: 50, 
			revert: true,
			revertDuration: 200, 
			opacity: 0.9
		});
	},
	closeCurrent : function() {
		var $close_icon = $("#kd_tabs .ui-tabs-selected.ui-state-active").find('.kd_tab_close');
		if( $close_icon.attr('id') === 'welcome_kd_tab_close' ){
			return false;
		}else{
			$close_icon.trigger('click');
		}
	}
 		
};


var __ft1 = Object.create(__k.fileTree);

var __ft2 = Object.create(__k.fileTree);
	
__ft2.options = {
	files_path		: "/",
	connector_url1	: "/task_ls.php",
	connector_url2	: "/k.php",
	_holder			: "#another_tree_holder",
	_tree			: "#another_tree",
	_holderHeight	: 0,
	_treeHeight		: 0,
	_item			: "<div class=\"k_filetree_item\"></div>",
	duration		: 200,
	_scrollBar		: false,
	_scrollBarPosY 	: 0,
	_scrollBarHeight: 0,
	_render_items	: "folders",
	_context		: false,
	_selectable 	: true,
	files_event		: "dblclick",
	folders_event	: "dblclick",
	show_hidden_files: false,
	_block_on_load	: true
}

__k.base.browserDetect.init();

/* !DOM READY */
jQuery(function($){
	if(top.location.search.search(/referrer/) !== -1){
		var href = top.location.search.split("?referrer=")[1];
		__k.utils.openInCommunity(decodeURIComponent(top.location.host + href));
	}
	
	__k.layout.initialize();
	__k.dashboard.init();
	__ft1.init_tree();
	
	var	$holder = $(__ft1.options._holder);
	$holder.rightClick(function(e) {
		e.stopPropagation();
		$holder.data("o",{type : "tree_holder", path: "/"});
		//__k.contextMenu._create($holder,e);
	});
	
	$holder.click(function(e) {
		e.stopPropagation();
		$holder.data("o",{type : "tree_holder", path: "/"});
		__k.contextMenu._create($holder,e);
	});

	$holder.parent().mouseenter(function(){
	    $holder.parent().find('.jScrollPaneDrag').fadeIn(400);	
	}).mouseleave(function(){
		$holder.parent().find('.jScrollPaneDrag').fadeOut(400);
	});	

	__k.tabs.create("#kd_tabs");

	$("#trigger_logout").click(function() {
		var url = __k.base.logOutUrl;
		
		
		var $dialog = $("div#kodingen_modal_box");
			
		$dialog.html("You're about to logout, are you sure?");
		$dialog.dialog({
			title : "Are you sure?",	
			bgiframe: true,
			resizable: false,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'Yes': function() {
					__k.utils.logout(url);
					$(this).dialog('close');
				},
				'No': function() {
					$(this).dialog('close');
					return false;
				}
			},
			close: function() {
				$(this).dialog('destroy');
			}
		}).show(400);
	});

	
	//AJAX GLOBAL LOADING IMAGE ON TOP LEFT CORNER OF AVATAR BLOCK, image appears whenever a jquery ajax event called
	 $(document).ajaxComplete(function(evt, request, settings){
	 	if(request.status === 404 || request.status === 500){
			__k.utils.loading("An error has occured while communicating with server. <span class='loading_close green'>[close]</span>",5000,true);
	 	}else if(request.status === 200){
			__k.utils.loading();
		}else{
			__k.utils.loading();
		}
	 }).ajaxStart(function(){
		__k.utils.loading("Working...");
	 }).ajaxError(function(){
		__k.utils.loading();
	 });

	var t = setInterval(function(){
		__k.utils.get_avatar_block();
	},600000);

/*
	var tt = setInterval(function(){
		$('html,body').scrollTop(0);
	},1000);
*/

/*
	var ttt = setTimeout(function(){
		__k.utils.loading();
		__k.utils.loading("Kodingen is on Wordpress Showcase please vote for us. <span class='loading_close green'>[close]</span>",5000,true);
	},10000);

*/
	//window.onbeforeunload = __k.utils.beforeUnload;

	//CREATE SHORTCUT KEYS
	$(document).bind('keydown', 'Ctrl+s', function (evt){$("#" + __k.tabs.currentTabPanelId + " .cm_save").trigger('click'); return false; });
	$(document).bind('keydown', 'Ctrl+w', function (evt){$("li.ui-tabs-selected div.kd_tab_close").trigger('click'); return false; } );
	$(document).bind('keydown', 'Ctrl+d', function (evt){__k.layout.section.toggle('dash'); return false;} );
	$(document).bind('keydown', 'Ctrl+f', function (evt){__k.layout.section.toggle('left'); return false; } );
	$(document).bind('keydown', 'Ctrl+e', function (evt){__k.layout.section.toggle('middle'); return false; } );
	$(document).bind('keydown', 'Ctrl+b', function (evt){__k.layout.section.toggle('bottom'); return false; } );
	$(document).bind('keydown', 'Esc'	, function (evt){__k.utils.closeModalAndCancel(); return false; } );

	var $command_line = $("#task_logger_command_line");
	$command_line.bind('keydown', 'return', function (evt){
		var msg_id = "msg_" + Math.floor(Math.random()*100);
		__k.utils.taskLogger.print(msg_id, __k.user.data.user_login + " > " + $(this).val() + "<br/>");
		var t = setTimeout(function() {
			__k.utils.taskLogger.print(msg_id,"You can't run shell commands because you are on a free account and on a shared environment. Go to <span class='log_action' onclick=\"__k.quickMenu.loadData('/kodingen/quickMenu/_overview_json.php');__k.layout.section.bottom.close();\">Account Overview</span> to find out more on setting up your own infrastructure.");
		},300);
		$(this).val("");
		return false; 
	});

	var postScriptsTimer = setTimeout(function() {
		$.getScript("/kodingen/js/jquery._post_plugins.js",function() {
			$("#trigger_feedback").show(400);
			__k.user.set_initial_ui_states();
			//130x58
			__k.layout.section.left.click_to_start.animate({"width":"156px", "height":"70px", "opacity":"1"},400,function() {
				__k.layout.section.left.click_to_start.animate({"width":"130px", "height":"58px"},100);	
				__k.base.get_version();
			});
		});
	},6000);
	
	if(__k.base.browserDetect.browser !== "Safari"){
		$('html,body').css({ "top":0,"left":0, "overflow":"hidden"});
	}else{
		$('html,body').css({ "position":"relative","top":0,"left":0, "overflow":"hidden"});
	}
/*
	if(navigator.userAgent.search(/safari/i) !== -1){
		$('html,body').css({ "top":0,"left":0});
	}else{
		$('html,body').css({ "position":"relative","top":0,"left":0});
	}
*/

	
	/*-------------
		OLD CODE 
	--------------*/
	
	//CLOSE MODAL BOXES AND UNBLOCKUI	
	$('.modal_close_button, .modal_close_form_button, .modal_close_link').click(function() { $.unblockUI(); return false; }); 

	//MODAL BOX SETTINGS
	var $parent_modal = $("#parent_modal_message")
	$parent_modal.draggable({ 
		handle: '#parent_modal_generic_header',
		cancel: 'div#parent_modal_generic_content, div#parent_modal_generic_content object, div#parent_modal_generic_content embed'
	});
	$('.modal_close_link').click(function() { __k.utils.closeModalAndCancel(); });

	//MAKE ALL ELEMENTS THAT HAS 'drag' CSS CLASS DRAGGABLE
	$(".drag").draggable({ stack: { group: '.default_widget', min: 50 }, cancel: '.nodrag'});    

});
