window.onload = load;
window.onunload = GUnload;

// ============= indexOf for IE =================
if(!Array.indexOf){
	Array.prototype.indexOf = function(obj){
		for(var i=0; i<this.length; i++){
			if(this[i]==obj){
				return i;
			}
		}
		return -1;
	}
};
// ==============================================

var app;

function load() {
//GLog.write(G_API_VERSION)

	app = new MApp;
	app.zoom = 4;
	app.centerPoint = new GLatLng(39.639538, -97.294922);
	app.container;
	app.map;
	app.pSelector;
	app.mController;
	app.ol2;
	app.zoomTimeout;

	app.onlogin = function() {
		app.pSelector.clearAll();
		app.mSelector.loadFranchises();
	};
}

function MApp() {
	this.self = this;
	this.serverScript = '/cgi-bin/controller.pl?';
};

MApp.prototype.userLogin = function(obj) {
	var self = this.self;
	var userId = document.getElementById('TextUn');
	var userPass = document.getElementById('TextPwd');
	var userNone = '-987654321';
	var http_request = false;
	
	var data = new Array();
	data[0] = userPass.value;
	data[1] = userId.value;
		
	if (userId) {	
		this.serverScript = '/cgi-bin/controller.pl?userId=' + userNone + '&pass=' + userPass.value;
		var url = app.serverScript + '&tt=0&task=login&r=' + Math.random() + '&userSn=' + userId.value;
		ajaxLoad(url,function(http_request){
			processResponse(http_request);
			if (typeof self.onlogin == 'function') {
				//self.onlogin();
				// Initialize packed or we get the word 'undefined'
				var packed = "";
				for (i = 0; (i < data.length); i++) {
					if (i > 0) {
						packed += ",";
					}
					packed += escape(data[i]);
				}
				document.data.data.value = packed;
				document.data.submit();
				
				//window.location = "/protected/main.html"
			}
		});
	}
};

function processResponse(http_request) {
	var txt = http_request.responseText;
	eval(txt);

	for (var n = 0 ; n < response.length ; n++ ) {
		var responseObj = response[n];
		var func = eval(responseObj.action);
		if (typeof func == 'function') {
			func(response[n]);
		}
	}
};

function setUserInfo(obj) {
	var txt = obj.dataStr;
	var rows = txt.split(';');
	var header = rows.shift();
	var fHeaderArray = header.split('|');

	if (rows.length) {
		var values = rows[0].split('|');
		var user = {};
		user.userId = values[fHeaderArray.indexOf('user_id')];
		user.screenName = values[fHeaderArray.indexOf('user_screen_name')];
		user.firstName = values[fHeaderArray.indexOf('user_first_name')];
		user.lastName = values[fHeaderArray.indexOf('user_last_name')];
		user.canCreate = values[fHeaderArray.indexOf('can_create')];
		user.key = values[fHeaderArray.indexOf('user_key')];
		
		app.user = user;
		app.serverScript = '/cgi-bin/controller.pl?userId=' + user.userId + '&key=' + user.key;
	}
};


