/**
 * ITzone - very main javascript object to manage most of behaviour
 * of ITzone website
 *
 * jQuery-fied Replacement for old Page object which is going to be removed soon
 *
 * @author XShady
 * @project itzone
 */
var ITzone = {};

/**
 * Class for handling server-side time
 *
 */
ITzone.time = {
	difference: 0,
	lang: {},

	/**
	 * Sets actual time (based on server-side time for e.)
	 *
	 */
	set: function(hours, minutes, seconds) {
        var serverDate = new Date();
		serverDate.setHours(hours, minutes, seconds);

		var serverTime = serverDate.getTime();
        var clientTime = new Date().getTime();

        this.difference = serverTime - clientTime;
	},

	/**
	 * Gets actual time, may differ from client-side time if this.set() was
	 * alredy used
	 *
	 */
	get: function()	{
	    return new Date().getTime() + this.difference;
	}
}


/**
 * Class for work with cookies
 *
 */
ITzone.cookie = {
	expires: null,
	path: null,
	domain: null,
	secure: null,

	/**
	 * Sets a cookie
	 *
	 */
	set: function(name, value) {
		document.cookie = name + "=" + escape(value) +
			((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
			((this.path == null) ? "" : ("; path=" + this.path)) +
			((this.domain == null) ? "" : ("; domain=" + this.domain)) +
			((this.secure == true) ? "; secure" : "");
	},

	/**
	 * Gets cookie by its name
	 *
	 */
	get: function(name)	{
		var arg = name + "=";
		var alen = arg.length;
		var clen = document.cookie.length;
		var i = 0;
		while (i < clen) {
			var j = i + alen;
			if (document.cookie.substring(i, j) == arg)
				return this.getByOffset(j);
			i = document.cookie.indexOf(" ", i) + 1;
			if (i == 0)
				break;
		}
		return null;
	},

	/**
	 * Gets a cookie by its offset, used internally by this.get()
	 *
	 */
	getByOffset: function(offset) {
		var endstr = document.cookie.indexOf(";", offset);
		endstr = (endstr == -1) ? document.cookie.length : endstr;

		return unescape(document.cookie.substring(offset, endstr));
	}
}

/**
 * User interface related stuff
 *
 */
ITzone.ui = {}

/**
 * Simple digital clock
 *
 */
ITzone.ui.clock = {
	elementId: '',

	/**
	 * Creates digital clock inside specified element
	 *
	 */
	create: function(elementId)	{
	    this.elementId = elementId;

	    $(document).ready(function() { setInterval('ITzone.ui.clock.step()', 500); });
	},

	/**
	 * Updates time information in clock element
	 *
	 */
	step: function() {
	    $('#' + this.elementId).get(0).innerHTML = this.getFormatedTime();
	},

	/**
	 * Returns formated time string
	 *
	 */
	getFormatedTime: function() {
		var objDate = new Date();
		objDate.setTime(ITzone.time.get());

		var h = objDate.getHours();
		var m = objDate.getMinutes();
		var s = objDate.getSeconds();

		h = (h == 0) ? '00' : h;
		m = (m <= 9) ? '0' + m : m;
		s = (s <= 9) ? '0' + s : s;

		return h + ":" + m + ":" + s;
	}
}

/**
 * Box with login form
 *
 */
ITzone.ui.loginBox = {
	elementId: '',
	userField: null,
	passField: null,

	create: function(elementId) {
	    this.elementId = '#' + elementId;
	    $(document).ready(function() { ITzone.ui.loginBox.init(); });
	},

	init: function() {
	    // Get fields
		this.userField = $(this.elementId + ' input').eq(0);
		this.passField = $(this.elementId + ' input').eq(1);
		// Set event handlers
		$(this.elementId).bind('submit', function() { return ITzone.ui.loginBox.onSubmit(); });
		this.userField.bind('focus', function() { return ITzone.ui.loginBox.fieldOnFocus('user'); });
		this.userField.bind('blur', function() { return ITzone.ui.loginBox.fieldOnBlur('user'); });
		this.passField.bind('focus', function() { return ITzone.ui.loginBox.fieldOnFocus('pass'); });
		this.passField.bind('blur', function() { return ITzone.ui.loginBox.fieldOnBlur('pass'); });
	},

	onSubmit: function() {
		return (this.userField[0].value != ITzone.lang.username
			&& this.userField[0].value != ''
			&& this.passField[0].value != '');
	},

	fieldOnFocus: function(fieldType) {
	    this.userField.addClass('active');
	    this.passField.addClass('active');

	    if (this.userField[0].value == ITzone.lang.username) {
	        this.userField[0].value = '';
	        this.passField[0].value = '';
	    }
	},

	fieldOnBlur: function(fieldType) {
	    this.userField.removeClass('active');
	    this.passField.removeClass('active');

	    if (this.userField[0].value == '') {
	        this.userField[0].value = ITzone.lang.username;
	        this.passField[0].value = ITzone.lang.password;
	    }
	    // if (fieldType == 'user') ...  -> not used yet but usefull
	}
}


ITzone.ajax = {
	submitForm: function(formName, callback) {
	    var url = ( $("form[name='" + formName + "']").attr('action') == '' )
			? document.location.href
			: $("form[name='" + formName + "']").attr('action');
        var params = $("form[name='" + formName + "'] *").serialize()
            + '&' + $("form[name='" + formName + "'] input:submit").eq(0).attr('name')
            + '=' + $("form[name='" + formName + "'] input:submit").eq(0).val()
            + '&ajax=1';
        
		$.ajax({
			type: "POST",
			url: url,
			data: params,
			success: callback
		});
	}
}


//
// Initialisation functions
//
ITzone.ui.init = function(options) {
	// Create digital clock in header
	if (options.uiClockId)
		ITzone.ui.clock.create(options.uiClockId);

	// Activate login box
    if (options.uiLoginBoxId)
		ITzone.ui.loginBox.create(options.uiLoginBoxId);
}

ITzone.init = function(options) {
    // Set time, if given
    if (options.timeSet)
        this.time.set(options.timeSet[0], options.timeSet[1], options.timeSet[2]);

	// Initialize user interface and pass options
	ITzone.ui.init(options);
}
