/** This is the maian class of Site Project
 * @Author Kassit.Com
 *  Date: 17 Feb 2008
 *  version 1.0
 */

var GlobalInterval;

function Core(){   							//Declare Main Class
	Core = this;
	this.maxBackward = '../../../../../../../../../';
	this.core = this.maxBackward + 'php/core.php';
	this.containers = new Array();
	this.container;
	this.mainContainer;
	this.door;
	this.notice;
	this.executer;
	this.head;
	this.foot;
	this.defaultLanguage;
	this.language;
	this.client = new Object();
	this.client.browser = new Object();
	this.client.ip;
	this.client.OS;
	this.client.country;
	this.client.username;
	this.client.access;
	this.viewport = new Object;
	this.authorized = false;
	this.url;
	this.error = '';
	this.shield;
	this.file;
	this.effector;
	this.script;
	this.scripts = new Array();
	this.publicTitle;
	this.extensionsPath = 'extensions/';
	this.extensions = new Array();
	this.validator;
	this.toolbar;
	this.conn;
}

Core.prototype =           												// Prototype class functions
{
	initialize: function(){
		this.script = document.getElementsByTagName('head')[0];
		this.url = this.parseURL();
		this.getClientInfo();
		this.initViewport();
		this.shield = new Shield();
		this.shield.show(lang.status['FirstLoading']);
		this.shield.fix();
		this.loadScripts("javascripts/Container.js;	" +
						 "javascripts/Executer.js; 	javascripts/File.js; 		"+
						 "javascripts/Forms.js;  	javascripts/Effector.js;	"+ 
						 "javascripts/highlight.js; javascripts/highslide.js;	"+
						 "javascripts/Shield.js;	javascripts/Components.js;	"+
						 "javascripts/Validator.js; javascripts/XHRConn.js;		"+
						 "javascripts/Menu.js;		javascripts/Toolbar.js");
	},
	
	checkScriptCompletion: function(){
		var SafeToOpen = true;
		for(scr=0; scr<this.scripts.length; scr++){
			if (this.scripts[scr].done == false)
				SafeToOpen = false;
		}
		if (SafeToOpen) {
			this.checkRequirements();
		}
		else
			window.setTimeout('Core.checkScriptCompletion()', 1000);
	},
	
	getClientInfo: function(){
		if (navigator.appVersion.indexOf("MSIE") != -1 || document.all) {
			this.client.browser.name = 'IE';
		}
		else if (navigator.userAgent.indexOf("Opera") != -1) {
			this.client.browser.name = 'Opera';
		}
		else if (navigator.userAgent.indexOf("Firefox") != -1 || (document.getElementById && !document.all)) {
			this.client.browser.name = 'Firefox';
		}
		else {
			this.client.browser.name = 'Unknown';
		}

		if (navigator.appVersion.toLowerCase().indexOf("win") != -1) 
			this.client.OS = 'Windows';
		else 
			this.client.OS = 'Unknown';

		this.client.javaEnabled = true;//navigator.javaEnabled();
	},
	
	setCoordinates: function(){
		var IE = document.all?true:false;
		if (!IE) document.captureEvents(Event.MOUSEMOVE)
			document.onmousemove = getMouseXY;
		var tempX = 0;
		var tempY = 0;
		function getMouseXY(e) {
			if (IE) { // grab the x-y pos.s if browser is IE
				tempX = event.clientX + document.body.scrollLeft;
				tempY = event.clientY + document.body.scrollTop;
			}
			else {  // grab the x-y pos.s if browser is NS
				tempX = e.pageX;
				tempY = e.pageY;
			}  
			if (tempX < 0){tempX = 0;}
			if (tempY < 0){tempY = 0;}  
			document.Show.MouseX.value = tempX;
			document.Show.MouseY.value = tempY;
			return true;
		}
	},
	
	is_child_of: function (parent, child) {
		if( child != null ) {			
			while( child.parentNode ) {
				if( (child = child.parentNode) == parent ) {
					return true;
				}
			}
		}
		return false;
	},
	
	onMouseOut: function (element, event, JavaScript_code) {
		var current_mouse_target = null;
		if( event.toElement ) {				
			current_mouse_target  = event.toElement;
		} else if( event.relatedTarget ) {				
			current_mouse_target  = event.relatedTarget;
		}
		if( !this.is_child_of(element, current_mouse_target) && element != current_mouse_target ) {
			eval(JavaScript_code);
		}
	},

	
	openContainer: function(type, URL, Params, checkAuth, title){
		if (this.containers.length > 0)
			this.acceptContainer();
		for(i=0; i<Core.containers.length; i++){
			if(URL == Core.containers[i].url){
				Core.containers[i].toFront();
				return false;
			}
		}
		var checkAuth = checkAuth == null?true:checkAuth;
		var num = this.containers.length;
		this.containers[num] = new container(num, type, URL, Params, checkAuth, title);
		this.container = this.containers[num];
		return this.containers[num];
	},
	
	acceptContainer:function(){
		for(i=0; i<this.containers.length; i++){
			this.containers[i].menu.cut();
			this.containers[i].style.position = 'absolute';
			this.containers[i].style.visibility = 'hidden';
		}
		return true;
	},
	
	removeContainer: function(Cnt){
		var num = Cnt.num;
		var tempConts = new Array();	
		var counter = 0;
		for(i=0; i<this.containers.length; i++){
			if(this.containers[i] != Cnt){
				tempConts[counter] = this.containers[i];
				counter = counter + 1;
			}	
		}
		Cnt.destroy();
		document.getElementById('ContentCenter').removeChild(Cnt.body);
		Cnt = null;
		counter = 0;
		this.containers = new Array();
		for(i=0; i<tempConts.length; i++){
			this.containers[i] = tempConts[i];
			this.containers[i].num = i;
			this.containers[i].id = this.containers[i].type + 'Container' + this.containers[i].num;
			document.getElementById(this.containers[i].body.id).setAttribute('id',this.containers[i].id)
		}
		this.executer.update();
		window.setTimeout('Core.containers[0].toFront();');
	},
	
	checkRequirements: function (){
		this.shield.setStatus(lang.status['CheckRequirements']);
		if(this.client.OS == 'Unknown'){
			alert(lang.errors['UnknownOS']);
			this.error = 'UnknownOS';
		}
		
		if(this.client.browser.name == 'Unknown'){
			alert(lang.errors['UnknownBrowser']);
			this.error = 'UnknownBrowser';
		}
		
		if (!this.client.javaEnabled){
			alert(lang.errors['JavaDisabled']);
			this.error = 'JavaDisabled';
		}
		this.conn = new XHRConn();
		this.conn.parent = this;
		this.conn.attachInfo = true;
		this.conn.send(this.core, '&action=checklogin', 
			function(R, Portal){
				Portal.forms = new Forms();
				Portal.executer = new Executer();
				Portal.validator = new FormValidator();
				Portal.effector = new Effector();
				Portal.file = new File();
				Portal.toolbar = new Toolbar();
				R = R.split('[]');
				Portal.client.username = R[0];
				Portal.client.access = R[1];
				if (Portal.client.access != 0) 
					Portal.authorized = true;
				else
					Portal.authorized = false;
					
				if (Portal.error == '') {
					Portal.mainContainer = Portal.openContainer('ajax', Portal.url['url']);
				}
				else{
					Portal.mainContainer = Portal.openContainer('frame', 'error/requirement.php?error=' + Portal.error, '', 
																 false, 'Kassit.Com > ' + lang.requirements[Portal.error]);
					Portal.mainContainer.enable();
				}
				Portal.fixBody();
				window.onresize = Portal.fixBody;
			}
		);
	},
   
	keyHandler: function (e,k){
		var asc = document.all ? event.keyCode : e.which;
		if(asc == k)	return true;
		else	return false;
	},
	
	fixBody: function(){
		Core.initViewport();
		Core.shield.fix();
		Core.toolbar.fix();
	},
	
	initViewport: function(nofixing){
		if (self.innerWidth) {
			this.viewport.width = self.innerWidth;
			this.viewport.height = self.innerHeight;
		} else if (document.documentElement&&document.documentElement.clientWidth) {
			this.viewport.width = document.documentElement.clientWidth;
			this.viewport.height = document.documentElement.clientHeight;
		} else {
			this.viewport.width = document.body.clientWidth;
			this.viewport.height = document.body.clientHeight;
		}
	},
	
	checkLogin: function(){
		this.conn.send(this.core, '&action=checklogin', 
			function(R, C){
				R = R.split('[]');
				C.client.username = R[0];
				C.client.access = R[1];
				if (C.client.access != 0) 
					C.authorized = true;
				else
					C.authorized = false;
			}, this);
	},
	
	register: function(u, p, e){
		this.forms.hide();
		this.shield.setStatus(lang.status['Wait']);
		var	Data = '&action=register&username=' + u + '&password=' + p + '&email=' + e;
		this.conn.send(this.core, Data,
			function(R,C){
				if(R.split('<>')[0] == 'registered' ){
					C.forms.close(true);
					C.reAuthPage();
					window.setTimeout('Core.openContainer(\'frame\',\'http://www.' + R.split('<>')[1] + '\',\'\',false,\'Confirmation\')',2000);
				}
				else{
					Core.forms.setStatus(lang.formErrors[R.split('<>')[1]], 'error');
					Core.forms.show();
				}
			}
		);
	},
	
	login: function(u, p){
		this.forms.hide();
		this.shield.setStatus(lang.status['LoggingIn']);
		var Data = '&action=login&username=' + u + '&password=' + p;
		this.conn.send(this.core, Data ,
			function(R, C){
				R = R.split('[]');
				if(R[0] == 'loggedin'){
					C.client.username = u;
					C.client.access = R[1];
					C.authorized = true;
					C.forms.close(true);
					C.reAuthPage();
				}
				else{
					Core.forms.setStatus(lang.formErrors[R[1]], 'error');
					C.forms.show();
				}
			},
			this
		);
	},
	
	logout: function(){
		var	Data = '&req=ajax&action=logout';
		this.conn.send(this.core, Data,
			function(R,C){
				C.client.username = 'Guest';
				C.client.access = 0;
				window.onscroll = null;
				C.authorized = false;
				
				for(i=0; i<C.containers.length; i++){
					if(C.containers[i].access != 0 && C.containers[i] != C.container){
						C.containers[i].close();
					}
				}
				if(C.container.access != 0)
					C.container.close();
				
		//		C.reAuthPage('door.open()');
			},
			this
		);
	},
	
	reAuthPage: function(){
		Core.container.reload();
		this.container.menu.stick();
	},
	
	handle: function(e,k,func){
		if(this.keyHandler(e,k)){
			window.setTimeout('Core.' + func,0.1);
		}
	},
	
	appendLogo: function(el,logo){
		document.getElementById(el).innerHTML = '<img border="0" src="../../../../../../../../../../../images/logos/'+logo+'" />';
	},
	
	parseURL: function(){
		URL = new Array();
		var Url = window.location.href;
		var URLSeg = Url.split('?');
		URL['protocol'] = URLSeg[0].split(':')[0];
		var mainAdd = URLSeg[0].substring((URL['protocol'].length + 3),(URLSeg[0].length - 1))
		URL['domain'] = mainAdd.split('.')[mainAdd.split('.').length - 1];
		if(URL['domain'].toLowerCase() == 'localhost')
			URL['host'] = 'localhost';
		else
			URL['host'] = mainAdd.split('.')[mainAdd.split('.').length - 2];
			
		if(URLSeg.length > 1){
			var safeString = new String(URLSeg[1].split('#')[0]);
			var URLParams = safeString.split('&');
			for(i=0; i<URLParams.length; i++){
				if(URLParams[i].indexOf('=') != -1){
					var nv = URLParams[i].split('=');
					URL[nv[0]] = nv[1];
				}
			}
			
			if (URL['url']) {
				if (URL['url'].indexOf('.php') == -1) {
					if (URL['url'].indexOf('/', URL['url'].length - 2) == URL['url'].length - 1) 
						URL['url'] += 'main.php';
					else 
						URL['url'] += '/main.php';
				}
				
			}
			else{
				URL['url'] = 'main.php'
			}
		}
		else{
			URL['url'] = 'main.php'
		}
		return URL;
	},
	
	correctURL: function(URL){
		var corrURL;
		if (URL.indexOf('.php') == -1) {
			if (URL.indexOf('/', URL.length - 2) == URL.length - 1) 
				corrURL = URL + 'main.php';
			else 
				corrURL = URL + '/'+'main.php';
		}else{
			corrURL = URL;
		}
		
		return corrURL;
	},
	
	appendImages: function(){
		var Div = document.createElement('div');
		Div.id = 'ImageContainer';
		Div.style.visibility = 'hidden';
		Div.style.position = 'absolute';
		Div.style.top = '0px';
		Div.style.left = '0px';
		Div.style.width = '0px';
		Div.style.height = '0px';
		document.body.appendChild(Div);
	},
	
	getContainerByName: function(name){
		for(i=0; i<this.containers.length; i++){
			if(this.containers[i].name == name)
				return this.containers[i];
		}
		return null;
	},
	
	getContainerById: function(id){
		for(i=0; i<this.containers.length; i++){
			if(this.containers[i].id == id)
				return this.containers[i];
		}
		return null;
	},
	
	getContainerByUrl: function(url){
		for(i=0; i<this.containers.length; i++){
			if(this.containers[i].url == url)
				return this.containers[i];
		}
		return null;
	},
	
	stop: function(){
		
	},
	
	centralize: function(el){
		this.initViewport();
		el.style.top = Math.round(this.viewport.height - el.style.height) / 2 + 'px';
		el.style.left = Math.round(this.viewport.width - el.style.width) / 2 + 'px';
	},
	
	loadScripts: function(src){
		if (src != '' && src != null) {
			var S = new String(src);
			var Scrpt = S.split(';');
			for (j = 0; j < Scrpt.length; j++) {
				var index = this.scripts.length;
				this.scripts[index] = document.createElement('script');
				this.scripts[index].type = 'text/javascript';
				this.scripts[index].src = Scrpt[j];
				this.script.appendChild(this.scripts[index]);
				this.scripts[index].done = false;
				this.scripts[index].parent = this;
				if (Core.client.browser.name == 'Firefox'){
					this.scripts[index].onload = function(){
													this.done = true
												}
				}
				else{
					this.scripts[index].onreadystatechange = function(){
						if (this.readyState == 'complete' ||
							this.readyState == 'loaded' ||
							this.readyState == 4){
							this.done = true;
						}
					}
				}
			}
			this.checkScriptCompletion();
		}
	}
}  // End of main Class Core



function addMethod(object, name, fn){
    var old = object[ name ];
    object[ name ] = function(){
        if ( fn.length == arguments.length )
            return fn.apply( this, arguments );
        else if ( typeof old == 'function' )
            return old.apply( this, arguments );
    };
}