
function isset() {
    var a = arguments, l = a.length, i = 0, undef;    
    if (l === 0) {
        throw new Error('Empty isset'); 
    }
    while (i !== l) {
        if (a[i] === undef || a[i] === null) {
            return false; 
        }
        i++;
    }
    return true;
}

var prevhash;

$(function(){
	// Bind an event to window.onhashchange that, when the hash changes, gets the
    // hash and adds the class "selected" to any matching nav link.
    $(window).hashchange( function(){
        //document.title = location.hash;
        //return;
        
        if(location.hash!=prevhash) {
            prevhash = location.hash;
            XOBAJAX.postObject(
                '/index.php?mode=fetchpage'
                , { page: location.hash }
                , function(res) {
                    var arr = JSON.parse(res);
                    if(isset(arr['title'])) {
                        var title = arr['title'];
                        document.title = title;
                    }
                    if(isset(arr['html'])) {
                        var html = arr['html'];
                        document.getElementById('idContent').innerHTML= html;
                    }
		    if(isset(arr['js'])) {
			    eval(arr['js']);
		    }
                }
                , 'POST'
            );
        }
    })
    
    // Since the event is only triggered when the hash changes, we need to trigger
    // the event now, to handle the hash the page may have loaded with.
    $(window).hashchange();
});

function fnTryJSON(json) {
    
    var out;
    
    try {
	out = JSON.parse(json);
    }
    
    catch (err) {
	out = {};
    }
    
    return out;
}

function isEmail(string) {
    if (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]+$/) != -1) {
        return true;
    } else {
        return false;
    }
}

function trim (str, charlist) {
    
    str = isset(str) ? str : '';
    charlist = isset(charlist) ? charlist : null;
    
    var whitespace;
    var l = 0;
    var i = 0;
    
    str += '';

    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    }

    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }

    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }

    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

