/**
 * Common javascript for Jandal Applications.
**/
Function.prototype.bind = function (obj) {
	var fn = this;
	return function () {
		var args = [this];
		for (var i = 0, ix = arguments.length; i < ix; i++) {
			args.push(arguments[i]);
		}
		return fn.apply(obj, args);
	};
};

function isArray(obj) {
    if (obj == null) return false;
    return obj.constructor == Array;
}

function notNull(obj) {
	return obj !== undefined;
}

jQuery.fn.swap = function(b) {
	b = jQuery(b)[0];
	var a = this[0],
		a2 = a.cloneNode(true),
		b2 = b.cloneNode(true),
		stack = this;
	 
	a.parentNode.replaceChild(b2, a);
	b.parentNode.replaceChild(a2, b);
	 
	stack[0] = a2;
	return this.pushStack( stack );
};

Array.prototype.contains = function (element) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == element) return true;
	}
	return false;
}

Array.prototype.intersect=function(){if(!arguments.length)return[];var a1=this;var a=a2=null;var n=0;while(n<arguments.length){a=[];a2=arguments[n];var l=a1.length;var l2=a2.length;for(var i=0;i<l;i++){for(var j=0;j<l2;j++){if(a1[i]===a2[j])a.push(a1[i]);}}a1=a;n++;}return a.unique();};Array.prototype.unique=function(){var a=[];var l=this.length;for(var i=0;i<l;i++){for(var j=i+1;j<l;j++){if(this[i]===this[j])j=++i;}a.push(this[i]);}return a;};

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

$.fn.replace = function(o) { return this.after(o).remove(); }; 
$.fn.hoverable = function(c) { this.hover(function(){ $(this).addClass(c); },
									      function(){ $(this).removeClass(c); }); return this; };

Object.clone = function(o) {
	if (typeof o != 'object' || o == null) return o;
	var n = {};
	for (var i in o) {
		n[i] = o[i]; 
	}
	return n;
}

// $.context
jQuery.extend({ context: function(context){
    var co = { callback: function (method) {
        if (typeof method == 'string') method = context[method];
        var cb = function () { method.apply(context, arguments); }
        return cb;
      }
    };
    return co;
  }
}); 

var app = {
	
	code: {success: 'success', failure: 'fail'},
	
	prefs: {
		assets : '/assets/'
	},
	
	timeout : {
		time : -1,
		obj	 : null,
		reset: function(){
			if(this.obj !== null){
				window.clearTimeout(this.obj);
			}
			if(this.time > 0)
				this.obj = window.setTimeout("app.timeout.complete()", this.time);		
		},
		complete: function(){
			document.location = "/autologout";
		}
	},

	ajaxAction: function(action, args, callback) {
		new app.Request('/ajax/'+action+'/?JSONRESPONSE&JSONREQUEST', 
					 $.extend({}, args, {submitted:1}), 
					 callback,
					 null,
					 'POST', 
					 'json');
	},

	randomHash: function() {
		var list = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'];
		var hash = "";
		for (var i = 0; i < 8; ++i) {
			hash += list[Math.floor(Math.random(0)*list.length)];
		}
		return hash;
	},
	
	growl : function(heading, msg, params){
		if(params == null) params = { position: 'bottom-right' };
		params.header = heading;
		$.jGrowl(msg, params);	
	},
	
	trimString : function(str, strlen){
    	var output = str;
    	if(str.length > strlen)
    		output = str.substr(0, strlen)+'...';
    	return output;
	},
	
	date : {
	
		unixtojs : function(unix){
			return $.datepicker.parseDate('@', parseInt(unix)*1000);	
		},
		
		compare : function(d1, d2){
			var one_day=1000*60*60*24;
			return Math.ceil((d1.getTime()-d2.getTime())/(one_day));
		},
		
		format:function(f, d){ return $.datepicker.formatDate(f, d); },
		dayShort : function(date){ return this.format('D', date); },
		dayNum : function(date){ return this.format('d', date); },
		monthShort : function(date){ return this.format('M', date); },
		monthLong : function(date){ return this.format('MM', date); },
		yearShort : function(date){ return this.format('y', date); },
		daydiff : function(start, end){ var diff = Math.ceil((end.getTime() - start.getTime())/(this.dayOffset))+1;
										return (diff + ' nights' + ((diff!=1)?'s':'')); }		
		
	},
	
    serialize : function(obj, re) {
        var result = [];
        $.each(obj, function(i, val) {
            if ((re && re.test(i)) || !re)
                result.push(i + ': ' + (typeof val == 'object' ? val.join 
                    ? '\'' + val.join(', ') + '\'' : app.serialize(val) : '\'' + val + '\''));
        });
        return '{' + result.join(', ') + '}';
    },

	// converts a serialized sting (JSON string) into an object. 
	// scope can hold extra parameters that can be evaluated in the string.

	unserialize : function(str, scope){
		return eval( '(' + str + ')' );
	},
	
	formatFilesize: function(size) {
		var i, units = ['b', 'kb', 'mb', 'gb'];
		for (i = 0; i < (units.length-1) && size>= Math.pow(1024, i+1); i++);
		return (Math.round(100 * size / Math.pow(1024,i))/100) + units[i];				
	},
	
	sortObjs : function(array, key, order){
		if(array == undefined || array == null) { console.debug('is null'); return null; } 
		var f1, f2;
		if(order=='ASC') { f1 = -1, f2 = 1; }
		else { f1 = 1, f2 = -1; }
		
		function sortFunc(a, b){
			if(isNaN(a[key]) && isNaN(b[key]))
		    	return evalStr(a[key],b[key]);
		    else return evalNum(a[key],b[key]);	
		}
		
		function evalStr(x,y){
			return ((x < y) ? f1 : ((x > y) ? f2 : 0));
		}
		
		function evalNum(x,y){
			return parseInt(y)-parseInt(x);
		}
		
		return array.sort(sortFunc);
	},
	
	popup : function(url){
		newwindow=window.open(url,'name','height=400,width=600,scrollbars=yes');
		if (window.focus) {newwindow.focus()}
	}
	
};
// do stuff to the dom when ready
$(function(){
	app.timeout.reset();
	$.datepicker.setDefaults({ dateFormat: 'dd-m-yy' }); 
	
	$('#rules_of_stay').click(function(){ app.popup('/rules'); return false; });
	$('#privacy_policy').click(function(){ app.popup('/privacy-policy'); return false; });
	$('#terms_and_conditions').click(function(){ app.popup('/terms-and-conditions'); return false; });
	
	

	
});

