if(!window.console) var console = window.firebug || {};
var onloads = [];
Date.prototype.dateAndHour = function() {
	var m = this.getMonth()+1;
	var d = this.getDate();
	var h = this.getHours();
	return ''+this.getFullYear()+'-'+(m<10?'0'+m:m)+'-'+(d<10?'0'+d:d)+'-'+(h<10?'0'+h:h);
};
Number.prototype.roundTo = function(dec) {
	return Math.round(this*Math.pow(10,dec))/Math.pow(10,dec);
};
document.getElementsByClass = function(classList, node) {		   
	if(document.getElementsByClassName)
		result = (node || document).getElementsByClassName(classList);
	else {
		var node = node || document,
			list = node.getElementsByTagName('*'),
			length = list.length, 
			classArray = classList.split(/\s+/),
			classes = classArray.length,
			result = [], i,j;
		for(i = 0; i < length; i++) {
			for(j = 0; j < classes; j++)  {
				if(list[i].className.search('\\b' + classArray[j] + '\\b') != -1) {
					result.push(list[i]);
					break;
				}
			}
		}
	}
	return result;
}

function GIS(){
	this.useFirebugLite = typeof(useFirebugLite)!='undefined' ? useFirebugLite : false;
	this.usePNGFix = typeof(usePNGFix)!='undefined' ? usePNGFix : false;
	this.defaultCitySearchStr = '';
	this.defaultCitySearchClose = '';
	this.defaultCitySearchLoadingText = '';
	this.weatherFactFrom = '';
	this.defined_user_city = {id:0, title:''};
	this.modules = [];
	this.loaded = {};
	this.GApiLoaded = false;
	this.GMapLoaded = false;
	this.title = '';

	this.ua = navigator.userAgent.toLowerCase();

	this.is_webkit = /(webkit)[ \/]([\w.]+)/.exec( this.ua );
	this.is_opera = /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( this.ua );
	this.is_msie = /(msie) ([\w.]+)/.exec( this.ua );

	this.is_chrome = typeof(chrome)!='undefined';
	this.is_opera = typeof(opera)!='undefined';
	this.is_firefox = !this.is_chrome && !this.is_opera && (window.navigator.appCodeName.match(/Mozilla/)!=null);

	this.static_path = 'static/';
	this.js_classes_path = this.static_path+'js/classes/';

	this.D = document;
	this.widget = null;

	this.modules = [];
	this.loaded = {};
	this.loadModulesSuccessCallBack = null;
	this.init();
}
GIS.prototype.init = function(){
	this.title = document.title;
	this.log(this.getConstructorName(this)+' class initialized.');
}
GIS.prototype.getConstructorName = function(obj){
	return this.is_msie ? obj.constructor.toString().replace(/^function /, '').replace(/[\n\r]/g, '').replace(/\(.+/gim, '') : obj.constructor.name;
}
GIS.prototype.registerAddFuncs = function(){
	if(typeof $ !== 'undefined'){
		$.flatten = function(arr){
			var data = [];
			$(arr).each(function(){
				data.push(this);
			});
			return arr;
		}
		$.extend({
			keys: function(obj){
				var a = [];
				$.each(obj, function(k){ a.push(k) });
				return a;
			}
		});
		$.removeFromArray = function(arr, ele){
			var in_arr = $.inArray(ele, arr);
			if(in_arr>-1) arr.splice(in_arr, 1);
			return arr;
		}
	}
}
GIS.prototype.loadModule = function(module, successCallBack){
}
GIS.prototype.loadModules = function(modules, successCallBack, par){
	var _loadModulesSuccess = function (){
		if(this.result!='none')
			this.obj.loaded[this.module.name] = 'ok';
		var loaded = true;
		$(this.obj.modules).each($.proxy(function(index2, obj2){
			loaded = loaded && (this.loaded[obj2.name]=='ok' || (this.loaded[obj2.name]!=='loading' && obj2.required===false));
		}, this.obj));
		if(this.module.property && this.module.name)
			if(window[this.module.name]){
				(par!=undefined?par:this.obj)[this.module.property] = new window[this.module.name]((par!=undefined?par:this.obj));
				// this.obj.log([par!=undefined?par:this.obj, this.module.property, (par!=undefined?par:this.obj)[this.module.property]]);
			} else
				this.obj.log(this.module.name+' is not defined', 'error');
		if(loaded && this.callback){
			$.proxy(this.callback(), this.obj);
		}
	}
	this.modules = modules;
	if($(this.modules).length>0){
		$(this.modules).each($.proxy(function(index, obj){
			this.loaded[obj.name] = 'loading';
		}, this));
		$(this.modules).each($.proxy(function(index, obj){
			par = (par!=undefined?par:this.obj);
			var context = {module:obj, obj:this, callback:successCallBack, par:par}
			if(!window[obj.name] || window[obj.name]==undefined){
				this.load_script({
					url:obj.url,
					context:context,
					success:$.proxy(_loadModulesSuccess, context),
					error:function(xhr){
						this.obj.loaded[this.module.name] = 'none';
						this.obj.log('Module '+this.module.name+' loaded with error "'+xhr.statusText+'"', 'error');
						$.proxy(_loadModulesSuccess, $.extend(context, {result:'none'}))();
					}
				});		
			} else
				$.proxy(_loadModulesSuccess, context)();
		}, this));
	} else {
		this.callback();
	}
}

GIS.prototype.log = function(arg, type){
	if(type=='' || type==undefined) type='log';
	if(window.console && window.console[type])
		window.console[type](arg);
}
GIS.prototype.storeInSession = function(arg, value){
	var data = {}; data[arg] = value;
	$.ajax({type: "post", data: data, url: "/avia_weather/set/"});
}
GIS.prototype.getFromSession = function(arg, callback){
	var callbackID = Math.round(Math.random()*10000);
	this['callback'+callbackID] = callback;
	$.ajax({
		type: "get",
		dataType: "json",
		context: {callbackID:callbackID, obj:this},
		data: {'arg': arg},
		url: "/avia_weather/get/",
		error: function(result) {
			var data = $.parseJSON(result.responseText);
			if(result.readyState==4 && result.status==200 && result.statusText=="OK" )
				if(this.obj['callback'+this.callbackID])
					this.obj['callback'+this.callbackID](data);
		},
		success: function(data) {
			if(this.obj['callback'+this.callbackID])
				this.obj['callback'+this.callbackID](data);
		}
	});
}
GIS.prototype.setHash = function(id){
		document.location.hash = id;
}
GIS.prototype.word_case = function(num, word1, word2, word3){
	if((num%100>4) && (num%100<21)) return word3;
	if(num%10==1) return word1;
	if((num%10>1) && (num%10<5)) return word2;
	return word3;
}
GIS.prototype.getCookie = function(rgxp_key, exact){
	var p = document.cookie.split(';'), r=new RegExp('^[ \t]*('+rgxp_key+')=([^;]*)(;|$)'), res=[];
	for(var i=0, l=p.length; i<l; i++){
		if(p[i].match(r))
			res.push({k:p[i].match(r)[1], v:p[i].match(r)[2]});
	}
	return res && res.length==1 && res[0].k===rgxp_key ? res[0].v : res;
	// return document.cookie.replace(new RegExp('^.*'+key+'=([^;]*)(;|$).*$', 'g'), '\1');
}
// findPos() borrowed from http://www.quirksmode.org/js/findpos.html
GIS.prototype.findPos = function(obj) {
	var curleft = curtop = 0;

	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}

	return({
		'x': curleft,
		'y': curtop
	});
}
GIS.prototype.renderRoundCorners = function(args){
	if(args.obj) var obj = args.obj;
	if(args.arcSize)
		var arcSize = args.arcSize;
	else
		var arcSize = Math.min(parseInt(obj.currentStyle['-moz-border-radius'] ||
		                                obj.currentStyle['-webkit-border-radius'] ||
		                                obj.currentStyle['border-radius'] ||
		                                obj.currentStyle['-khtml-border-radius']) /
		                       Math.min(obj.offsetWidth, obj.offsetHeight), 1);
	if(args.fillColor)
		var fillColor = args.fillColor;
	else
		var fillColor = obj.currentStyle.backgroundColor;
	if(args.fillSrc)
		var fillSrc = args.fillSrc;
	else
		var fillSrc = obj.currentStyle.backgroundImage.replace(/^url\("(.+)"\)$/, '$1');
	if(args.strokeColor)
		var strokeColor = args.strokeColor;
	else
		var strokeColor = obj.currentStyle.borderColor;
	if(args.strokeWeight)
		var strokeWeight = args.strokeWeight;
	else
		var strokeWeight = parseInt(obj.currentStyle.borderWidth);
	if (!document.namespaces.v) { document.namespaces.add("v", "urn:schemas-microsoft-com:vml"); }

	// obj.className = obj.className.concat(' ', classID);
	// alert(arcSize+', '+fillColor+', '+fillSrc+', '+strokeColor+', '+strokeWeight);
	var stroked = 'true';
	if (isNaN(strokeWeight)) {
		strokeWeight = 0;
		strokeColor = fillColor;
		stroked = 'false';
	}

	obj.style.background = 'transparent';
	obj.style.borderColor = 'transparent';

	// Find which element provides position:relative for the target element (default to BODY)
	var el = obj;
	var limit = 100, i = 0;
	while ((typeof(el) != 'unknown') && (el.currentStyle.position != 'relative') && (el.tagName != 'BODY')) {
		el = el.parentElement;
		i++;
		if (i >= limit) { return(false); }
	}
	var el_zindex = parseInt(el.currentStyle.zIndex);
	if (isNaN(el_zindex)) { el_zindex = 0; }
	//alert('got tag '+ el.tagName +' with pos '+ el.currentStyle.position);

	var rect_size = {
		'width': obj.offsetWidth - strokeWeight,
		'height': obj.offsetHeight - strokeWeight
	};
	var el_pos = this.findPos(el);
	var obj_pos = this.findPos(obj);
	obj_pos.y = obj_pos.y + (0.5 * strokeWeight) - el_pos.y;
	obj_pos.x = obj_pos.x + (0.5 * strokeWeight) - el_pos.x;

	var rect = document.createElement('v:roundrect');
	rect.arcsize = arcSize +'px';
	rect.strokecolor = strokeColor;
	rect.strokeWeight = strokeWeight +'px';
	rect.stroked = stroked;
	rect.style.display = 'block';
	rect.style.position = 'absolute';
	rect.style.top = obj_pos.y +'px';
	rect.style.left = obj_pos.x +'px';
	rect.style.width = rect_size.width +'px';
	rect.style.height = rect_size.height +'px';
	rect.style.antialias = true;
	rect.style.zIndex = el_zindex - 1;

	var fill = document.createElement('v:fill');
	fill.color = fillColor;
	fill.src = fillSrc;
	fill.type = 'tile';

	rect.appendChild(fill);
	el.appendChild(rect);

	var css = el.document.createStyleSheet();
	css.addRule("v\\:roundrect", "behavior: url(#default#VML)");
	css.addRule("v\\:fill", "behavior: url(#default#VML)");

	isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
	// IE6 doesn't support transparent borders, use padding to offset original element
	if (isIE6 && (strokeWeight > 0)) {
		obj.style.borderStyle = 'none';
		obj.style.paddingTop = parseInt(obj.currentStyle.paddingTop || 0) + strokeWeight;
		obj.style.paddingBottom = parseInt(obj.currentStyle.paddingBottom || 0) + strokeWeight;
	}

	if (typeof(window.rounded_elements) == 'undefined') {
		window.rounded_elements = new Array();

		if (typeof(window.onresize) == 'function') { window.previous_onresize = window.onresize; }
		window.onresize = this.window_resize;
	}
	obj.element.vml = rect;
	window.rounded_elements.push(obj.element);
}
GIS.prototype.window_resize = function(){
	if (typeof(window.rounded_elements) == 'undefined') { return(false); }

	for (var i in window.rounded_elements) {
		var el = window.rounded_elements[i];

		var strokeWeight = parseInt(el.currentStyle.borderWidth);
		if (isNaN(strokeWeight)) { strokeWeight = 0; }

		var parent_pos = findPos(el.vml.parentNode);
		var pos = findPos(el);
		pos.y = pos.y + (0.5 * strokeWeight) - parent_pos.y;
		pos.x = pos.x + (0.5 * strokeWeight) - parent_pos.x;

		el.vml.style.top = pos.y +'px';
		el.vml.style.left = pos.x +'px';
	}

	if (typeof(window.previous_onresize) == 'function') { window.previous_onresize(); }
}
GIS.prototype.createSelection = function(field, start, end) {
    field.select();
    if( field.createTextRange ) {
        var selRange = field.createTextRange();
        selRange.collapse(true);
        selRange.moveStart('character', start);
        selRange.moveEnd('character', end-start);
        selRange.select();
    } else if( field.setSelectionRange ) {
        field.setSelectionRange(start, end);
    } else if( field.selectionStart ) {
        field.selectionStart = start;
        field.selectionEnd = end;
    }
    field.focus();
}
GIS.prototype.load_script = function(args){
	$.ajax({
		url: args.url,
		dataType: 'script',
		async: false,
		context: args.context?args.context:null,
		success: args.success?args.success:function(){},
		error: args.error?args.error:function(){}
	});
}

var gis = {};
var site = {};

gis = new GIS();
site = gis;
if(typeof $ !== 'undefined')
	gis.registerAddFuncs();
else {
	onloads.push(function(){
		gis.registerAddFuncs();
	});
}

