var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.isSupported = (this.browser == "Safari" || this.browser == "Firefox" || this.browser == "Explorer"  || this.browser == "Mozilla");
		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: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			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.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();


var workspace = {
  Version: '1.0.1',
  require: function(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
  },
  load: function() {
    var path = $('worspaceScript').src.replace(/workspace\.js.*$/, "");
    "window,window_ext,effects,Widgets,behaviour,autotree,ResponseHandler.class,Workspace.class,dragdrop,icon".split(',').each(
      function(include) { workspace.require(path+include+'.js');}
    );     
  }
}
workspace.load();

Ajax.Responders.register({
    onCreate: function() {
      if(Ajax.activeRequestCount> 0){
    	$('loadingGif').style.display = 'block';
      }
    },
    onComplete: function() {
      //Behaviour.apply();
      if(Ajax.activeRequestCount == 0){
    	$('loadingGif').style.display = 'none';
      }
    }
  }
);

window.onbeforeunload = function (evt) {
  var message = 'Are you sure you want to leave?';
  if (typeof evt == 'undefined') {
    evt = window.event;
  }
  if (evt) {
    evt.returnValue = message;
  }
  return message;
}

/**** HELPER FUNCTIONS FOR EVERYONE ****/
window.getWidth = function(){
	if( typeof( window.innerWidth ) == 'number' ) {
	  //Non-IE
	  return window.innerWidth;
	} else if( document.documentElement &&
		( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	  //IE 6+ in 'standards compliant mode'
	  return document.documentElement.clientWidth;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	  //IE 4 compatible
	  return document.body.clientWidth;
	}
	return false;
}

window.getHeight = function(){
	if( typeof( window.innerWidth ) == 'number' ) {
	  //Non-IE
	  return window.innerHeight;
	} else if( document.documentElement &&
		( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	  //IE 6+ in 'standards compliant mode'
	  return document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	  //IE 4 compatible
	  return document.body.clientHeight;
	}
	return false;
}

//create global variables
var currentTree;
var showFileControlTimer;
var Rules = {};
var dialogWindowParams = {
  className: "mac_os_x",
  width: 350,
  height: 150,
  resizable: false,
  closable: false,
  minimizable: false,
  maximizable: false,
  draggable: true
};

Event.observe(window, 'load', 
	function(event){
		$('loadingGif').style.display = 'none';	//hiding the loading thing when the login screen is shown!

		//check for browser support we currently only want to support IE and Firefox
		if(!BrowserDetect.isSupported)
		{
			dialogWindowParams = Object.extend(dialogWindowParams, {title: "Workspace", height: 200});
			Dialog.alert('<h2>Browser Not Support</h2>Your browser is currently not supported. Please use Internet Explorer 5.0+ or Firefox 1.0+', 
				{
					windowParameters: dialogWindowParams, 
					okLabel: "Ok", 
					ok: function(win){ 
						window.location = "browserRequirements.php";
						return;
					}
				}
			);
			return;
		}
    if(loginRequired==false){
       initializeDesktop();
			 return true;
    }
		dialogWindowParams = Object.extend(dialogWindowParams, {title: "Workspace ", height: 200});
		Dialog.alert($('login').innerHTML, 
			{
				windowParameters: dialogWindowParams, 
				okLabel: "Login", 
				cancelLabel: "cancel", 
				ok: function(win){ 
					if($F('loginEmail')=="" || $F('loginPassword')=="") return false;
          if(login(Form.serialize("loginForm"))){
						//Login succeeded
						initializeDesktop();
						return true;
					}else{
						//Login failed
						$('login_error_msg').innerHTML='Authentication Failed. Please ensure you have entered the appropriate email/password.'; 
						$('login_error_msg').show(); 
						//Dialog.win.updateHeight(); 
						//new Effect.Shake('modal_dialog');
						$('loginPassword').focus();
						$('loginPassword').select();
						return false;
					}
				}
			}
		);
		
	}//onload handler
);

function login(pars){
	var url = "login.php";
	var myAjax = new Ajax.Request(url,
		{
			method: "post",
			parameters: pars,
			asynchronous: false
		}
	);
	var response = ResponseHandler.handleResponse(myAjax.transport.responseText);
	if(response.responseType=="success") return true;//Login succeeded
	return false;//Login failed
}
function logout(){
	var url = "logout.php";
	var myAjax = new Ajax.Request(url,
		{
			method: "post",
			asynchronous: false
		}
	);
	window.onbeforeunload = null;
	document.location = "index.php";
}

function initializeDesktop(){
	var desktopObject = $('desktop');
	desktopObject.style.height = window.getHeight() + 'px';
	var iconItem = Icon.create('newWS','images/workspaceIcon.png','Create New Workspace',desktopObject);
	iconItem.setHandler(function(){
		 showCreateWorkspaceWindow();
		});

	
	var iconItem = Icon.create('BlogIcon','images/rss.gif','Blog',desktopObject);
	iconItem.setHandler(function(){
		 showWidget("widgets/wsRSS.php", "Blog", 375, 210);
		});
	
	var iconItem = Icon.create('reportBug','images/reportBug.png','Bug/Feature Request',desktopObject);
  iconItem.setHandler(function(){
		 showWidget("widgets/reportBug.php", "Report a Bug", 350, 300);
		});
  var iconItem = Icon.create('changePassword','images/login.png','Change Password',desktopObject);
  iconItem.setHandler(function(){
		 showWidget("widgets/changePassword.php", "Change Your Password", 350, 200);
		});
	var iconItem = Icon.create('Logout','images/exit.gif','Logout',desktopObject);
	iconItem.setHandler(function(){
          var x = Dialog.confirm("Are you sure you want to log off?? <BR>This action will also closed all open files and any unsaved changes will be lost.",
            {
              windowParameters: dialogWindowParams,
              ok: function(){			
        				logout();
              }
            }
          );
	});

	/*desktopObject.oncontextmenu = function(event){
		if(window.event) event = window.event;
		Tree.hideAllMenus();
		Tree.isMenuOpen = true;
		var menu = Menu.create();

		var menuItem = MenuItem.create();
		menuItem.setText("Open Workspace");
		menuItem.setHandler(
		function(){
		 showCreateWorkspaceWindow();
		}
		);
		menu.addMenuItem(menuItem);

		menuItem = MenuItem.create();
		menuItem.setText("Themes");
		menu.addMenuItem(menuItem);

		var nestedMenu = Menu.create();
		menuItem.addMenu(nestedMenu);

		menuItem = MenuItem.create();
		menuItem.setText("Green");
		menuItem.setHandler(
			function()
			{
				Windows.windows.each( 
					function(w) 
					{
						var id = w.getId();
						var currentTheme = w.getClassName();
						w.changeClassName('theme2'); 
					}
				);
//				Dialog.alert("Workspace Settings will appear here!", {windowParameters: {width:300, height:100}, okLabel: "close", ok:function(win) {return true;}});
			}
		);
		nestedMenu.addMenuItem(menuItem);


		menuItem = MenuItem.create();
		menuItem.setText("Purple");
		menuItem.setHandler(
			function()
			{
				Windows.windows.each( 
					function(w) 
					{
						var id = w.getId();
						var currentTheme = w.getClassName();
						w.changeClassName('mac_os_x'); 
					}
				);
//				Dialog.alert("Workspace Settings will appear here!", {windowParameters: {width:300, height:100}, okLabel: "close", ok:function(win) {return true;}});
			}
		);
		nestedMenu.addMenuItem(menuItem);


		//make the rest of the menu here
		menu.setPosition(Event.pointerX(event), Event.pointerY(event));
		//menu.show();
		return false;
	}*/
	
	Workspace.createAndShowWindow();
	new Workspace();
	CodePress.loadScript(document, "js/dynamic/GetFTPConnections.js.php", 
	 function(){
	   try{
  	 if(openFTPConnections){
    	 openFTPConnections.each(
    	   function(host){new Workspace(host);}
    	 );
  	 }
  	}catch(e){}
	 }
	);


	var windowObserver = {
	  onStartResize: function(eventName, win){
	    if(win.getId()==Workspace.windowId){
	      Workspace.contentPane.style.overflow = "hidden";
	    }
	  },
    onEndResize: function(eventName, win){
	    if(win.getId()==Workspace.windowId){
	      $('Workspaces').style.overflow = "auto";
	      var windowHeight = win.getSize().height;
	      var workspacePaneHeight = windowHeight - 50;
	      $('Workspaces').style.height = workspacePaneHeight+"px";
	    }else if(win.options.isEditor){
	      win.options.editor.updateSize(win);
	    }
	  },
    onBeforeClose: function(eventName, win){
      if (win.options.isEditor && win.options.editor.isDirty()){
  		  return confirm("This file contains unsaved changes. Are you sure you want to close it?");
  	  }
  	  return true;
    },
    onStartMove: function(eventName, win){
	    //win.setOpacity(1.0);	we dont' want opacity effect when dragging .. too much resource hogger!
	    if(win.getId()==Workspace.windowId) Tree.hideAllMenus(); 
	  },
	  onEndMove: function(eventName, win){
	    //Make sure the user hasn't moved the window out of the top-left corner
	    var desiredLocation = win.getLocation();
	    win.setLocation(Math.max(desiredLocation.top.replace(/px/, ""), this.__buffer), Math.max(desiredLocation.left.replace(/px/, ""), this.__buffer));
	  },
	  onClose: function(eventName, win){
	   if(win.isMinimized()){
	     var windowIndex;
        for(i=0; i<this.minimizedWindows.length; i++){
	        if(this.minimizedWindows[i]==win){
            windowIndex = i;
            break;
          }
	      }
	      if(windowIndex!=null && windowIndex<this.minimizedWindows.length){//Make sure the index is valid
	        //Remove this window element, and adjust all subsequent windows, both in the array, and their screen position
	        this.minimizedWindows.splice(windowIndex, 1);
	      }
	      this.positionAll();
	   }
	  },
	  onMinimize: function(eventName, win){
	    if(win.isMinimized()){
	      win.oldClassName = win.getClassName();
	      win.previousLocation = win.getLocation();
	      win.previousSize = win.getSize();
	      var newTitle = win.oldTitle = win.getTitle();
	      if(newTitle.length>this.__maxTitleLength) newTitle = win.oldTitle.substr(0, this.__maxTitleLength)+"...";
	      win.setTitle(newTitle);
        $(win.getId()).style.width = this.__minimizedWindowWidth + "px";
	      $(win.getId()).style.height = "0px";
	      win.changeClassName('disabled');
	      this.minimizedWindows.push(win);
	    }else{
        if(win.oldTitle) win.setTitle(win.oldTitle);
        if(win.previousLocation) win.setLocation(win.previousLocation.top.replace(/px/, ""), win.previousLocation.left.replace(/px/, ""));
	      if(win.previousSize){
          $(win.getId()).style.width = win.previousSize.width + "px";
	        win.setSize(win.previousSize.width, win.getSize().height);
        }
        if(win.oldClassName) win.changeClassName(win.oldClassName);
        //Find this window in the array of currently minimized windows
        var windowIndex;
        for(i=0; i<this.minimizedWindows.length; i++){
	        if(this.minimizedWindows[i]==win){
            windowIndex = i;
            break;
          }
	      }
	      if(windowIndex!=null && windowIndex<this.minimizedWindows.length){//Make sure the index is valid
	        //Remove this window element, and adjust all subsequent windows, both in the array, and their screen position
	        this.minimizedWindows.splice(windowIndex, 1);
	      }
	    }
	    this.positionAll();
	  },
	  positionAll: function(){
	    var pageSize = WindowUtilities.getPageSize();
	    var yLocation = pageSize.pageHeight - windowObserver.__minimizedWindowHeight - windowObserver.__buffer;
      windowObserver.minimizedWindows.each(
	      function(win, index){
          var xLocation = index * windowObserver.__minimizedWindowWidth + windowObserver.__buffer - (20 * (index+1));
	        $(win.getId()).style.top = yLocation + "px";
	        $(win.getId()).style.left = xLocation + "px";
	      }
	    );
	  },
	  onWindowResize: function(){
	    windowObserver.positionAll();
	  },
	  __maxTitleLength: 20,
	  __buffer: 2,
	  __minimizedWindowHeight: 33,
	  __minimizedWindowWidth: 230,
	  minimizedWindows: new Array()
	}
	Windows.addObserver(windowObserver);
  Event.observe(window, "resize", windowObserver.positionAll);
}//initializeDesktop

function updateWidgetWindow(id){
    var window = Windows.getWindow(id);
    if(!window) return false;
    
    window.updateHeight();
    window.updateWidth();
}
function showCreateWorkspaceWindow(){
    var params = Object.extend({}, dialogWindowParams);
    params = Object.extend(params, {title:"Add Workspace", height: 260, width: 400, resizable: true, closable: false});
    Dialog.confirm(
      {
        url: "createWorkspace.php",
        options: {method: "post"}
      } ,
      {
        windowParameters: params,
        ok: function(){
          var host = $F('host');
          if(!host || host=="") return false;
          var pars = Form.serialize('createWorkspaceForm');
          if(Workspace.addFTPConnection(host, pars)){
            new Workspace(host);
            return true;
          }else{
            alert("Could not connect to the specified FTP server using those parameters. Please try again");
            return false;
          }
        }
      }
    );
}//showCreateWorkspaceWindow

function showWidget(_url, _title, _w, _h)
{
	var windowId = "widget" + _title;
	if($(windowId)){
		Windows.getWindow(windowId).toFront();
		return;
	}
	var widgetWindow = new Window(windowId , 
	{
		url: _url,
		className: "mac_os_x", 
		closable: true, 
		resizable: true,
		minimizable: true,
		maximizable: true,
		title: _title, 
		width:_w, 
		height:_h, 
		opacity:1.0
	});
	widgetWindow.setDestroyOnClose();
	widgetWindow.showCenter();
}
