if (!window.console) {
  console = {log: function() {}};
}

$.postJSON = function(url, data, callback) {
    $.post(url, data, callback, "json");
};

var $data = function(key, value) {
    return $('body').data(key, value);
};

var getPath = function() {
    return location.href.substring(0,location.href.lastIndexOf("/")+1);
};

var explodeQueryString = function(query) {
    var paramList = query.split("&");
    var params = {};
    var index = paramList.length;
    while (index--) {
        var param = paramList[index];
        var foundEq = param.indexOf("=");
        params[param.substr(0, foundEq)] = param.substr(foundEq+1);
    }
    return params;
};


 /*
 * Merges one object hash into another.  Any fields in 'to' that are also in
 * 'from' will be overwritten.
*/

var mergeProperties = function(to, from) {
    if (!to || !from) { 
        return to || from; 
    } 
    for (var x in from) { 
        to[x] = from[x]; 
    } 
    return to;
};

 /*
 * Formats a string based on an object hash:
 * >>> "Fruit: %{fruit}, Color: ${color}".format({fruit: 'Apple', color: 'Red'})
 * <<< "Fruit: Apple, Color: Red"
*/
String.prototype.format = function(dict) {
    result = this;
    for (key in dict) {
        var re = new RegExp("\\${" + key + "}", "g");
        result = result.replace(re, dict[key]);
    }
    return result;
};

String.prototype.capitalize = function()
{
    return this.charAt(0).toUpperCase() + this.slice(1);
};

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
};
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
};
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
};

 /*
 * From:
 * jQuery Form Plugin
 * version: 2.28 (10-MAY-2009)
 * @requires jQuery v1.2.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 * Resets the form data.  Causes all form elements to be reset to their original value.
*/

$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};

 /*
 * End jQuery Form Plugin includes
*/
 
 /*
 * Serializes the first match to an object hash, if it is a form.
 * Each key is the name of an :input element, or id if name is null.
 * Each value is the result of val() on that input element.
*/
$.fn.serializeObject = function() {
    var results = {};
    
    $(this[0]).find(":input").each(function(){
        var key = $(this).attr("name") || $(this).attr("id");
        var value = $(this).val();
        if (key && value) results[key] = value;
    });
    
    return results;
};

var serialize = function(object) {
    for (var key in object) {
        var value = object[key];
        console.log(key, value);
    }
};

var isEmailAddress = function(value) {
    return value.indexOf("@") > -1 && value.indexOf(".") > -1;
};

var stripslashes = function(str) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // +   input by: Rick Waldron
    // +   reimplemented by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: stripslashes('Kevin\'s code');    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
    return (str+'').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
            case '\\': return '\\';
            case '0': return '\0';
            case '': return '';
            default: return n1;
        }
    });
};

function goodEscape(string) {
    return encodeURIComponent(string || ""); //.replace(/%20/g, '+');
}

function goodUnescape(string) {
    return decodeURIComponent(string ? string.replace(/\+/g, '%20') : "");
}

function explodeQueryString(qs) {
    qs = new String(qs || location.search);  // TODO: jslint doesn't like this--using string as a constructor.
    qs = qs.replace('?','');
    var qsObj = {};
    var qsArr = qs.split('&');
    var index = qsArr.length;
    while (index--) {
        // TODO(niels) Deal with multiple entries 
        var arg = qsArr[index].split('=');
        if (arg.length === 2) {
            qsObj[goodUnescape(arg[0])] = goodUnescape(arg[1]);
        } else if (arg.length === 1) {
            qsObj[goodUnescape(arg[0])] = '';
        }
    }
    // TODO(Niels) figure out how we want to add the fragment identifier, at this point we can just throw it in qsObj like this:
    // qsObj.fragmentID = location.pathname.replace('#','');
    return qsObj;
}

function implodeQueryParameters(queryParameters) {
    var queryString = '';
    for (var x in queryParameters) {
        if (queryParameters.hasOwnProperty(x) && x) {
            queryString += (queryString ? '&' : '?') + goodEscape(x) + "=" + goodEscape(''+queryParameters[x]);
        }
    }
    return queryString;
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
};

function eraseCookie(name) {
  createCookie(name,"",-1);
}


/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Base64 = {
 
    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
 
        input = Base64._utf8_encode(input);
 
        while (i < input.length) {
 
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
 
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
 
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
 
            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
        }
 
        return output;
    },
 
    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
 
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
        while (i < input.length) {
 
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));
 
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
 
            output = output + String.fromCharCode(chr1);
 
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
 
        }
 
        output = Base64._utf8_decode(output);
 
        return output;
 
    },
 
    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
 
        for (var n = 0; n < string.length; n++) {
 
            var c = string.charCodeAt(n);
 
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
 
        }
 
        return utftext;
    },
 
    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
 
        while ( i < utftext.length ) {
 
            c = utftext.charCodeAt(i);
 
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
 
        }
 
        return string;
    }
 
};

function truncate(str, length) {
    if (str.length > length) {
        return str.substr(0, length) + "...";
    }
    else {
        return str;
    }
}

function $set_radio_val($radio_group, val) {
    $radio_group.filter("[value='" + val + "']").click();
}

