// init.js

/* ideas and certain code borrowed from JSAN package */

/*
	resources and resources_path must be defined
	before the App object is created at the end 
	of the init.js file

	These variables are application specific, but
	should be viable application / site wide since
	we're simply defining parameters of available resources.
*/

var resources = {};

resources['ui.dialog'] 			= {js: 'dialogs.js', css:'dialogs.css'};
resources['ui.tabpane'] 		= {js: 'tabpane.js', css:'tab.css'};
resources['ui.calendar'] 		= {js: 'calendar.js'};

resources['lib.prototype'] 		= {js: 'prototype-1.4.0.js'};
resources['lib.scriptaculous.builder'] 	= {js: 'builder.js'};
resources['lib.scriptaculous.controls'] = {js: 'controls.js'};
resources['lib.scriptaculous.dragdrop'] = {js: 'dragdrop.js'};
resources['lib.scriptaculous.effects'] 	= {js: 'effects.js'};
resources['lib.scriptaculous.unittest'] = {js: 'unittest.js'};
resources['lib.png'] 			= {js: 'pngfix.js'};
resources['lib.cookies'] 		= {js: 'cookies.js'};
resources['lib.db'] 			= {js: 'db.js'};
resources['lib.jsan'] 			= {js: 'jsan.js'};
resources['lib.querystring'] 		= {js: 'querystring.js'};
resources['lib.mvc'] 			= {js: 'mvc.js'};
resources['lib.utils'] 			= {js: 'utils.js'};
resources['lib.behaviour'] 		= {js: 'behaviour.js'};
resources['lib.json'] 			= {js: 'json.js'};


resources['tools.geocoder'] 		= {js: 'geocoder.js'};
resources['tools.gmap.kmap'] 		= {js: 'kmap.js', css: 'kmap.css'};
resources['tools.gmap.pdmarker'] 	= {js: 'pdmarker.js'};
resources['tools.gmap.smoothscroll'] 	= {js: 'smoothscroll.js'};

resources['app.logic.world.sighting']		= {js: 'sightingmvc.js' };
resources['app.logic.world.hotspot']		= {js: 'hotspotmvc.js' };
resources['app.logic.world.club']		= {js: 'clubmvc.js' };
resources['app.logic.world.user']		= {js: 'usermvc.js' };

var resources_path = '/resources/';

/* Symbols are necessary for IE */

var symbols = {};

symbols['lib.scriptaculous.builder'] = ['Builder'];
symbols['lib.scriptaculous.controls'] =['Autocompleter', 'Ajax', 'Field', 'Form'];
symbols['lib.scriptaculous.dragdrop'] =['Droppables', 'Draggables', 'Draggable', 'SortableObserver', 'Sortable'];
symbols['lib.scriptaculous.effects'] =['String','Element','Array','Effect','Effect2'];
symbols['lib.scriptaculous.unittest'] =['Event','Test'];

symbols['lib.png'] = ['correctPNG'];
symbols['lib.json'] = [];

symbols['lib.cookies'] = ['getCookie','setCookie','delCookie'];

/* need to setup a namespace here!! */
symbols['lib.db'] = ['xmlToObjects','loadXmlData','checkError','isIE','isMoz',
		     'applyObject', 'date_string', 'short_date_string', 'mysqldate2js',
		     'short_months', 'num2mon', 'jsdate2mysql'];
		     
symbols['lib.jsan'] = ['JSAN'];
symbols['lib.querystring'] = ['Querystring', 'Querystring_get'];

symbols['tools.geocoder'] = ['isIE', 'isMoz', 'Geocoder', 'gotCaPlaces', 'thegeocoder', 'geogo'];
symbols['tools.gmap.kmap'] = ["geobirds_gmap","GMap2"];
/*
symbols['tools.gmap.pdmarker'] = ['getPdMarkerRevisionInfo','getPdMarkerVersion', 'getPdMarkerShortVersion', 
				      'pdMarkerOpenList', 'PdMarkerAddDetailWinOpen', 'PdMarkerClose',
				      'latLongToPixel', 'GMap', '_mSiteName', 'PdMarker', 'setObjOpacity',
				      'idToElemId', 'initTooltip', 'initDetailWin', 'setTTPosition', 'getClientWidth' ];
*/
symbols['tools.gmap.pdmarker'] = ['getPdMarkerVersion', 'getPdMarkerShortVersion', 'APIkey', 'getGoogleMapsVersion',
				'latLongToPixel', 'pdMarkerExtList', 'PdMarkerAddToExtList', 'PdMarkerRemoveFromExtList', 
				'PdMarkerFindInExtList', 'PdMarkerClose', 'PdMarkerBlinkOnOff', 'isPdMarker', 
				'getPdMarkerCount', 'shorten', 'poweredByClick', 'poweredByMouseover', 'getPoweredBy', 
				'setPoweredBy', 'GMap2'];

symbols['tools.gmap.smoothscroll'] = ['exO','GMap2', 'hookMouseWheelHandlers', 'zoom', 'clamp'];

symbols['ui.calendar'] = ['Calendar', 'calendar2'];

symbols['ui.tabpane'] = ['hasSupport','WebFXTabPane','WebFXTabPage','setupAllTabs','disposeAllTabs'];
symbols['ui.dialog'] = ['isIE','isMoz','alertDialog','confirmDialog','alertX','alertY',
			'MyAppAlertSetXY', 'MyAppAlertXY', 'MyAppAlertInit', 'MyAppConfirmInit',
			'MyAppAlert', 'GeoBirdsBasic2ChoiceDialog', 'GeoBirdsBasicVeilDialog',
			'GeobirdsErrorAlert', 'GeobirdsWarningAlert', 'GeobirdsInfoConfirm', 
			'Geobirds2ChoiceConfirm', 'Geobirds2ChoiceWarning', 'doShowGeobirds2Choice', 
			'doShowGeobirdsAlert', 'jt_DialogBox', 'jt_AppAlert', 'jt_AppConfirm',
			'String', 'jt_fixE', 'jt_Point', 'jt_getOffsetXY', 'jt_moveTo', 
			'jt_divOnScrn', 'Drag'];

symbols['lib.mvc'] = ['Observer','View','Controller','Model','CollectionModel','MVCEvent'];
symbols['lib.utils'] = ['Utils'];
symbols['lib.behaviour'] = ['Behaviour', 'getAllChildren'];


symbols['app.logic.world.sighting'] = ['SightingModel', 'SightingCollectionModel', 'SightingListView', 'SightingMapView'];
symbols['app.logic.world.hotspot'] = ['HotspotModel' ,'HotspotCollectionModel', 'HotspotListView'];
symbols['app.logic.world.club'] = ['ClubModel', 'ClubCollectionModel', 'ClubListView'];
symbols['app.logic.world.user'] = ['UserModel', 'UserCollectionModel', 'UserListView'];


/*
	App package manager inspired by JSAN.  Observes more lenient 
	requirements in terms of resource interface structures.
*/
App = function(res, thepath) {
	this._loaded = {};
	this._callbacks = {};
	this.path = thepath;
	this.resources = res;
};

App.prototype.call = function(pkg,method,obj,args) {
	if (!this.resources[pkg]) alert('Invalid package : ' + pkg);
	else {
		this._callbacks[pkg] = {};
		this._callbacks[pkg].method = method;

		this._callbacks[pkg].obj = obj;
		this._callbacks[pkg].args = args;
		this.use(pkg);
	}
}

App.prototype.use = function(pkg) {	
	if (!this.resources[pkg]) {
		alert('Invalid package : ' + pkg);
	} else {
		if (!this._loaded[pkg]) {
			
			var res = this.resources[pkg];
			if (res) {
//			        var loadfunc = (App.isIE) ? this.loadIEfile : this.loadfile;
			        var loadfunc = this.loadIEfile;
			        
				if (res.js) loadfunc.apply(this,[pkg, res.js, App._newScript]);
				if (res.css) loadfunc.apply(this, [pkg, res.css, App._newStyle]);
			}
		} else {
			// alert('cache hit - ' + pkg);
		}
		this._onLoadComplete(pkg);
	}
}	

App.prototype.loadfile = function(pkg,file,constructor) {
    try{
    	var script = constructor.call(App);
        var text = new App.Request().getText(this._pkg2path(pkg,file));
	script.innerHTML = text;
	App._appendHead(script);        
    } catch (e) {
        throw e;
    }
}

App.prototype.loadIEfile = function(pkg,file,constructor) {
    if (constructor == App._newStyle) {
    	var link = document.createElement('link');
    	link.rel = "stylesheet";
    	link.type = "text/css";
    	link.href = this._pkg2path(pkg,file);
    	App._appendHead(link);
    } else {
    	var text = new App.Request().getText(this._pkg2path(pkg,file));
    	eval(text);
    	for (var i = 0; i < symbols[pkg].length; i++) {
    		window[symbols[pkg][i]] = eval(symbols[pkg][i]);
    	}	
    }
}

App.prototype._onLoadComplete = function(pkg) {	
	this._loaded[pkg] = true;
	var c = this._callbacks[pkg];

	if (c && c.method) {
		c.obj[c.method].apply(c.obj,c.args);
	}
}

App.prototype._pkg2path = function(pkg,file) {
    	return this.path + App._convertPackageToPath(pkg) + '/' + file;
}

App._newStyle = function() {
    var style = document.createElement('style');
    style.type = 'text/css';
    return style;
}

App._newScript = function() {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    return script;
}

App._appendHead = function(child) {
    var head = document.getElementsByTagName("head")[0];
    head.appendChild(child);
}

App.isIE = (navigator.appName.indexOf("Microsoft") != -1);
App.isMoz = (navigator.appName.indexOf("Netscape") != -1);

/*
	This code borrowed from JSAN package
	http://openjsan.org
*/
App._convertPackageToPath = function (pkg) {
    return pkg.replace(/\./g, '/');
}

App.globalScope = self;

// Low-Level HTTP Request
App.Request = function (jsan) {
    if (App.globalScope.XMLHttpRequest) {
        this._req = new XMLHttpRequest();
    } else {
        this._req = new ActiveXObject("Microsoft.XMLHTTP");
    }
}

App.Request.prototype = {
    _req:  null,

    getText: function (url) {
        this._req.open("GET", url, false);
        try {
            this._req.send(null);
            if (this._req.status == 200 || this._req.status == 0) {
                return this._req.responseText;
            }
        } catch (e) {
            alert("File not found: " + url);
            return null;
        };

        alert("File not found: " + url + ' status: ' + this._req);
        return null;
    }
};


var app = new App(resources, resources_path);

