/**
* BuzzDash Page common class
*/
function BDP ()
{
    this.U_id = undefined;
    this.AU_id = undefined;
}

/**
* Get compiled lang message
* @uses lang/{lang}/messages.js
* @param string key message key
* @param string args args for compile
*/
BDP.getMessage = function (key, args)
{
    var msg = this.messages[key];
    if (args && args.constructor == Array) {
         for (var i = 0; i < args.length; i++) {
             var re = new RegExp("\\{" + (i + 1) + "\\}", "g");
             msg = msg.replace(re, args[i]);
         }
    }
    return msg;
}

/**
* Display message
* @todo write as inline window box
* @param string key message key
* @param string args args for compile
*/
BDP.message = function (key, args)
{
    var msg = (key in this.messages)? this.getMessage(key, args) : key;
    // todo
    alert(msg);
}

/**
* Handle js errors
* @todo write
*/
BDP.error = function (msg, desc, data, type)
{
    try {
        //alert("Unexpected error:\n" + msg + "\n");

        var oJsr = new Jsr();
        //oJsr.onload = function(){ BDP.go() };

        var params = {
            'BROWSER': {
                'url': document.location.href,
                'cookie': document.cookie,
                'userAgent': navigator.userAgent,
                'cookieEnabled': navigator.cookieEnabled,
                'time': (new Date).getTime(),
                'date': (new Date).toString()
            },
            'BDP': {
                'U_id': BDP.U_id,
                'AU_id': BDP.AU_id,
                'C_id': BDP.C_id
            },
            'message': msg,
            'description': desc,
            'data': data
        };
        oJsr.call('misc', 'error', params);

    } catch (e) {
        return;
    }
}

BDP.getCookies = function (init)
{
    var cookies = {};
    var pairs = document.cookie.split(/\s*;\s*/);

    var duplicated = 0;
    var subdomains = document.location.hostname.split(".");
    for (var i=0; i<pairs.length; i++) {
        var nv = pairs[i].split("=");
        if (nv[0] in cookies) {
        	var domain = subdomains[subdomains.length - 1];
        	for (var j=3; j<=subdomains.length; j++) {
        		var domain = subdomains.slice(-j).join(".");
        		document.cookie = nv[0] + "=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=." + domain + ";";
        		if (domain == document.location.hostname) {
        			document.cookie = nv[0] + "=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/;";
        		}
        	}
        	
            //document.cookie = nv[0] + "=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=" + domain;
            duplicated++;
            continue;
        }
        cookies[nv[0]] = nv[1];
    }
    /*
    if (duplicated) {
        document.location.href = document.location.href;
    }
    */
    return cookies;
}


BDP.setCookie = function(name, value, life)
{
    var date = "";
    if (value === undefined || value === null) {
        value = "";
        date = "expires=Thu, 01-Jan-1970 00:00:01 GMT";
    } else if (life) {
        var d = new Date();
        d.setTime(d.getTime() + life * 1000);
        date = "expires=" + d.toGMTString();
    }

    var rootDomain = "." + document.location.hostname.split(".").slice(-2).join(".");
    document.cookie = name + "=" + value + "; " + date + "; path=/; domain=" + rootDomain;
}
/**
* Navigate to bd page
* @param string page    Page name
* @param array params   Optional additional params
* @param bool get       If true, will return the generated url string instead of redirecting.
* @return mixed         Void or string if get set to true
* @todo abs url
*/
BDP.go = function (page, params, get, win, full)
{
    var url;
    if (params === undefined) {
        params = {};
    }
    
    if (page == "buzzbite") {
        throw("For buzzbite page pass url.");
    }
   
    if (! page) {
        page = "home";
    }

    if (page.match('^https?://') || (BDP.site && page.indexOf(BDP.site) == 0)) {
        url = page;
    } else if (! BDP.mapping.enabled) {
        url = BDP.site + "/index.php";
        params["page"] = page;
    } else if (BDP.mapping['pages'][page] === undefined)  {
        url = BDP.site + (page.charAt(0) == "/"? "" : "/") + page;
    } else {
        if (typeof BDP.mapping['pages'][page] != "object") {
            url = BDP.mapping['pages'][page];
        } else {
            // 1st as default
            for (var secondParam in BDP.mapping['pages'][page]) {
                for (var secondParamValue in BDP.mapping['pages'][page][secondParam]) {
                    url = BDP.mapping['pages'][page][secondParam][secondParamValue];
                    break;
                }
            }
            // if set
            for (var secondParam in BDP.mapping['pages'][page]) {
                if (params[secondParam]) {
                    url = BDP.mapping['pages'][page][secondParam][params[secondParam]];
                    delete params[secondParam];
                    break;
                }
            }
        }
        url = BDP.site + "/" + (url? url + "/" : "");
        
    }
    
    var pairs = new Array();
	for (var key in params) {
	    if (params[key]) {
		  pairs[pairs.length] = key + "=" + encodeURIComponent(params[key]);
	    }
	}
	if (pairs.length > 0) {
	    url += (url.indexOf("?") == -1 && url.charAt(url.length - 1) != "/")? "/" : "";
	    url += url.indexOf("?") != -1? "&" : "?";
	    url += pairs.join("&");
	}
	if (full && url.indexOf(document.location.protocol + ":") == -1) {
	    url = document.location.href.substring(0, document.location.href.indexOf(BDP.site)) + url;
	}
	if (get) {
	    return url;
	} // else

	win = win? win : top;
	win.location.href = url;
}


BDP.init = function ()
{
    // check cookies
    BDP.cookies = BDP.getCookies(1);

    /* REGISTER AU */
    if (BDP.U_id) {
        return;
    }
    if (BDP.AU_id) {
        return;
    }
    // test cookie enabled
    BDP.setCookie("_test", "1", 20);
    if ((document.cookie.indexOf("_test=1") == -1)) {
        BDP._cookieDisabled = true;
        BDP.AU_id = undefined;
        return false;
    }

    // request
    var oJsr = new Jsr();
    var params = {
        'time': (new Date()).getTime()
    }
    oJsr.onresults = function()
    {
        var AnonUsr = this.results.registerAU;
        if (typeof(AnonUsr) == "string") {
            try {eval(AnonUsr)}catch(e){}
            return;
        }
        if (AnonUsr == false) {
            BDP.error("Couldn't register guest user");
            return;
        }
        BDP.AU_id = AnonUsr['AU_id'];
        var AU_hash = AnonUsr['AU_hash'];
        BDP.setCookie("AU[AU_id]",  BDP.AU_id, 10*365*24*60*60);
        BDP.setCookie("AU[AU_hash]",  AU_hash, 10*365*24*60*60);
    };
    //var params = {'AU_hash': AU_hash};
    oJsr.call('misc', 'registerAU');
}
