/*
 Namespaces
*/

if (typeof hive == 'undefined') hive = {}

hive.namespace = function(ns)
{
    var np = '', p = ns.split('.');
    for(k in p){
        (np != '') ? np += '.' + p[k] : np  = p[k];
        eval("if (typeof " + np + " == 'undefined') " + np + " = {}");
    }
}

hive.ns = hive.namespace;

/*
  Globals
*/

$(function(){

    var data = $('#template-data');

    // user
    hive.ns('hive.globals.user');
    hive.globals.user.id = $(data).attr('data-user-id');
    hive.globals.user.group = $(data).attr('data-group-id');
    hive.globals.user.smallAvatar = $(data).attr('data-small-avatar');

    // profile
    hive.ns('hive.globals.profile');
    hive.globals.profile.id = $(data).attr('data-profile-id');

    // template
    hive.ns('hive.globals.template');
    hive.globals.template.url = $(data).attr('data-template-url');

    // req-key
    hive.globals.reqkey = $(data).attr('data-req-key');

    // social networks
    hive.globals.facebookApiKey = $(data).attr('data-facebook-api-key');
    hive.globals.vkontakteApiKey = $(data).attr('data-vkontakte-api-key');

    // session key
    hive.globals.sessionId = $(data).attr('data-session-id');

    // static domain
    hive.globals.staticDomain = $(data).attr('data-static-domain');
});

/*
  Functions for soy templates
 */
hive.raw = function(s)
{
    return eval(s);
}

hive.isOwner = function(userId)
{
    return (0 != userId  && userId == hive.globals.user.id);
}

hive.isAdmin = function()
{
    return hive.globals.user.group == 1;
}

// poor i18n
function __(s){
    return s;
}

// noticer
hive.noticer = {
    show: function(msg){
        if ($('.b-noticer').length == 0)
            $('body').append(hive.views.noticer(msg))
        $('.b-noticer').html(msg).fadeIn('slow');
        setTimeout(function(){
            $('.b-noticer').fadeOut('slow')
            }, 4000);
    }
}

// ajax results cacher
hive.ajaxCachedCalls = [];

// ajax
hive.ajax = function(params)
{
    var key = params.url;
    if (params.data != undefined)
        key += hive.utils.serialize(params.data);

    if (params['cache-call'] == undefined || params['cache-call']){

        if (hive.ajaxCachedCalls[key] != undefined){
            if (params.onSuccess != undefined)
                params.onSuccess(hive.ajaxCachedCalls[key]);
            if (params.onComplete != undefined)
                params.onComplete();
            return true;
        }
        
    } else {
        hive.ajaxCachedCalls[key] = undefined;
    }

    if (params.onComplete == undefined)
        params.onComplete = function(){}
    
    var defaults = {
        cache: false,
        dataType: 'json',
        type: 'post',
        error: function(d){
            if (d.msg != undefined)
                hive.noticer.show(d.msg);
            else
                hive.noticer.show(__('Ошибка. Возможно вам не хватает прав для совершения операции.'));
        },
        timeout: function(){
            hive.noticer.show(__('Запрос не выполнился. Таймаут.'));
        },
        success: function(d){
            if (d.state == 'success'){
                this.onSuccess(d);
                hive.ajaxCachedCalls[key] = d;
            } else if (d.msg != undefined){
                hive.noticer.show(d.msg);
            } else {
                hive.noticer.show(__('Запрос не выполнился'));
            }
        },
        complete: function(){
            params.onComplete()
        },
        onSuccess: function(d){} // you can override
    }

    $.ajax($.extend({}, defaults, params));
}

// utils
hive.ns('hive.utils');
hive.utils.serialize = function( mixed_value ) {
    var _getType = function( inp ) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            if (match = cons.match(/(\w+)\(/)) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';

    switch (type) {
        case "function":
            val = "";
            break;
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") {
                    continue;
                }
                okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
                vals += hive.utils.serialize(okey) +
                hive.utils.serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") val += ";";
    return val;
}

// social networks

$(function(){

    // FB
    $('body').prepend('<div id="fb-root"></div>');
        
    window.fbAsyncInit = function() {
        FB.init({
            appId: hive.globals.facebookApiKey,
            status: false,
            cookie: true,
            xfbml: true
        });
    }

    var el = document.createElement('script');
    el.type = "text/javascript";
    el.src = 'http://connect.facebook.net/ru_RU/all.js';
    el.async = true;
    document.getElementById("fb-root").appendChild(el);

    // VK
    $('body').prepend('<div id="vk_api_transport"></div>');

    window.vkAsyncInit = function() {
        VK.init({
            apiId: hive.globals.vkontakteApiKey
        });
    };
    
    setTimeout(function() {
        var el = document.createElement("script");
        el.type = "text/javascript";
        el.src = "http://vk.com/js/api/openapi.js";
        el.async = true;
        document.getElementById("vk_api_transport").appendChild(el);
    }, 0);

});

// add url parsing to strings

String.prototype.parseUrl = function()
{
	var matches = this.match(arguments.callee.re);

	if ( ! matches ) {
		return null;
	}

	var result = {
		'scheme': matches[1] || '',
		'subscheme': matches[2] || '',
		'user': matches[3] || '',
		'pass': matches[4] || '',
		'host': matches[5],
		'port': matches[6] || '',
		'path': matches[7] || '',
		'query': matches[8] || '',
		'fragment': matches[9] || ''};

	return result;
};

String.prototype.parseUrl.re = /^(?:([a-z]+):(?:([a-z]*):)?\/\/)?(?:([^:@]*)(?::([^:@]*))?@)?((?:[a-z0-9_-]+\.)+[a-z]{2,}|localhost|(?:(?:[01]?\d\d?|2[0-4]\d|25[0-5])\.){3}(?:(?:[01]?\d\d?|2[0-4]\d|25[0-5])))(?::(\d+))?(?:([^:\?\#]+))?(?:\?([^\#]+))?(?:\#([^\s]+))?$/i;

hive.utils.getParamFromUrlHash = function(url, paramName)
{
    var hash = url.parseUrl().fragment;

    if (!hash)
        return false;

    if (hash.indexOf('&') != -1){
        var pairs = hash.split('&');
        var params = [];
        for(var k in pairs){
            var args = pairs[k].split('=');
            if (args.length == 2)
                params[args[0]] = args[1];
        }
        if (params[paramName] == undefined)
            return false;

        return params[paramName];
    } else {
        
        var args = hash.split('=');
        if (args.length < 2 || args[0] != paramName)
            return false;
        return args[1];
    }
}
