/**
 * func.js
 * @author Dusan Jakub
 * 
 * Some common routines includes in every page
 */

/**
 * Include for JS
 */
function include(filename)
{
	var head = document.getElementsByTagName('head')[0];
	
	script = document.createElement('script');
	script.src = web_root+'/'+filename;
	script.type = 'text/javascript';
	
	head.appendChild(script)
}


$(document).ready(function () {
  // Replace class=button with real buttons
  $("a.button").each(function () {
    var href = $(this).attr("href");
    var onclick = $(this).attr("onclick");
    var caption = $(this).text();
    $(this).replaceWith($("<button>"+caption+"</button>")
      .click(function() { 
        if (onclick) 
          onclick();
        else 
          location.href = href; 
        }));
    });


  // Common AJAX setup
  $.ajaxSetup({
    error: function (xmlhttp) {
      data = xmlhttp.responseText;
      switch (xmlhttp.status)
      {
        case 401:
          alert("Due to your inactivity, you have probably been logged off by the server. \n\nThe page will now reload.");
          window.location.href=window.location.href;
          break;
        case 404:
        case 500:
          try {
            var json = JSON.parse(data);
            alert("Error: "+json.error);
          }
          catch (error) {
            alert ("Error: " + data);
          }
          break;

        default:
          alert(data);
          alert("Error code: " + xmlhttp.status);
      }
    },

    dataFilter: function (data, type) {
      if (type == "json")
      {
        //alert(data);
        try {
          var json = JSON.parse(data);
          
          if (json.status == "error")
          {
            alert("Error: "+json.error);
            if (typeof this.serverError != "undefined")
              this.serverError();
            return false;
          }
          else
            return json;
        }
        catch (error) {
          alert ("Unable to parse data:" + data);
          return false;
        }
      }
      return data;
    }
  });
});