/* 
 * Global functions and variables
 * 
 * @author Milos Djekic (mdjekic@gmail.com)
 * @see http://linkedin.com/in/mdjekic
 */

function doNothing() {}

var base_url = "";
var radio_count = 0;

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

function writeRadioButton(name,value,checked) {
    if(!checked) checked_attr = "";
    else checked_attr = "checked";
    var id = radio_count++;
    var radio = '<input id="radio_'+id+'" style="display:none" type="radio" name="'+name+'" value="'+value+'" '+checked_attr+' />';
    document.write(radio);
    radio = $("#radio_"+id);
    var img_src = base_url+"images/";
    if(checked) {
        img_src += "NotSureCheckBoxChecked.jpg";
        checked = 1;
    }
    else {
        img_src += "NotSureCheckBox.jpg";
        checked = 0;
    }
    var img = $('<a title="'+checked+'" href="javascript:doNothing()"><img border="0" src="'+img_src+'" /></a>');
    img.click(function(){
        if($(this).attr("title") == 1) return;
        $("[name = '"+name+"']").each(function(){
            if($(this).get(0) == radio.get(0)) {
                $(this).attr('checked', 'checked');
                $(this).next().find("img").attr("src",base_url+"images/NotSureCheckBoxChecked.jpg");
                return;
            }
            $(this).removeAttr("checked");
            $(this).next().find("img").attr("src",base_url+"images/NotSureCheckBox.jpg");
            $(this).next().attr("title",0);
        });
    });
    radio.after(img);
}

// todo: error handler
function callService(url,params,type,callback) {
    $.ajax({
        "url": url,
        "type": type,
        "dataType": "json",
        "data": params,
        "success": callback,
        "error": function(result) {
            debug(result);
        }
    });
}

function debug(obj) {
    if (window.console && window.console.log) window.console.log(obj);
}
