/**
 * Javascript class for handling basic AJAX method. Can handle GET or POST methods of comunication
 * This code is based on the one publiced on web http://www.openjs.com/articles/ajax_xmlhttp_using_post.php.
 *
 * @author Dzaky
 * @date 2009-01-15
 * @version 0.1 testing
 * @licence i don't "care", so based on source (inspiration code)
 */
var ajaxHandler = "";
var debug = false;
var ajaxLoaderImage = documentRoot+"/style/shared/ajax-loader.gif"

function ajaxClass() {
  this.http = "";
  this.url = documentRoot+"/web/ajax/";
//  this.url = location.host+"/web/ajax/";
  this.element = "";
  this.params = "";
  this.handler = "";
  this.method = "post";



  /**
   * Initialize XMLHttpRequest based on type of browser. Should be able to
   * handle IE, FF, Opera & Netscape.
   *
   * @date 2009-01-15
   * @return pointer to XMLHttpRequest object
   */
  this.getHTTPObject = function() {
    http = false;
    //Use IE's ActiveX items to load the file.
    if(typeof ActiveXObject != 'undefined') {
      try {http = new ActiveXObject("Msxml2.XMLHTTP");}
      catch (e) {
        try {http = new ActiveXObject("Microsoft.XMLHTTP");}
        catch (E) {http = false;}
      }
      // If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla
      // etc. to load the document.
    } else if (XMLHttpRequest) {
      try {http = new XMLHttpRequest();}
      catch (e) {http = false;}
    }
    return http;
  }


  /**
   * Procedure for AJAX get method
   *
   * @date 2009-01-15
   * @return no return value
   */
  this.getMethod = function() {
    this.http.open("GET", this.url+"?"+this.params, true);
    this.http.onreadystatechange = this.handler;
    this.http.send(null);
  }


  /**
   * Procedure for POST get method
   *
   * @date 2009-01-15
   * @return no return value
   */
  this.postMethod = function() {
    this.http.open("POST", this.url, true);

    document.location.hash = "#"+this.handler;
    urlHash = document.location.hash;

    //Send the proper header infomation along with the request
    this.http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    this.http.setRequestHeader("Content-length", this.params.length);
    this.http.setRequestHeader("Connection", "close");

    this.http.onreadystatechange = eval( innerHandler );

    this.http.send(this.params);

  }



  this.setParams = function(str) {
    this.params = str;
  }
  this.setHandler = function(str) {
    this.handler = str;
    ajaxHandler = str;
  }
  this.setMethod = function(str) {
    this.method = str;
  }
  this.setElement = function(str) {
    this.element = str;
  }
  this.execute = function() {
    this.http = this.getHTTPObject();

    loadingAjax(); // zobrazime "loading" div

    if(this.method=="post") {
      this.postMethod();
    } else {
      this.getMethod();
    }
  }
}  // konec tridy




/**
 * Handler for recieved data from server.
 *
 * @date 2009-01-15
 * @return no return value
 */
innerHandler = function() {
  if(http.readyState == 4 && http.status == 200) {
    var str = http.responseText;
    var handler = ""+ajaxHandler;

    try {
      eval( ajaxHandler+"(str)" );
      unLoadAjax();
    }catch(err){
      if( debug ) window.alert("Chyba: " + err.message);
    }
  }
}




/**
 * Nasledujici cast kodu se stara o hlidani kotev a v pripade zmeny vola
 * prislusnou stranku
 */
var urlHash = "";
var homePage = true;  // prvni nacteni teto stranky

setInterval("checkAnchor()", 300);

function checkAnchor(){
  // kontrola jestli se zmenilo navesti
  if(urlHash != document.location.hash && document.location.hash!=""){
    urlHash = document.location.hash; // nastavime zmenenou kotvu
    homePage = false; // uz byla ajaxem volana jina stranka, nechceme se zacyklit

    var splits = urlHash.substring(1).split('&');
    var section = splits[0];

    // zavolame funkci pro ziskani dat
    var func = section+"_handler";
    this[func]();
  }

  // pokud byl navrat na uvodni stranku
  if(document.location.hash=="" && homePage==false){
    document.location.reload();  // reloadujeme stranku
    homePage = true;  // aby se cyklicky nevracel na stranku
  }
}




/**
 * Standartni metoda pro ziskani dat ze serveru pomoci AJAXu
 */
var globAjax = new ajaxClass();
function getData(handler, element) {
  globAjax.setHandler( handler );
  globAjax.setElement( element );
  globAjax.setParams( 'action='+handler );
  globAjax.execute();

  return false;
}




/**
 * Listener na udalost kliknuti na danem elementu
 * Nacte ID elementu a zavola funkci ktera se jmenuje  'elementId'_handler
 * napriklad element ma ID 'mujElement', handler na toto bude 'mujElement_handler'
 */
function onclickHandler(e) {
  var targ;
  if (!e) {
    var e = window.event;
  }
  if (e.target) {
    targ = e.target;
  } else if (e.srcElement) {
    targ = e.srcElement;
  }
  // defeat Safari bug
  if (targ.nodeType == 3) {
    targ = targ.parentNode;
  }

  var elementId = targ.id;
  var func = elementId+"_handler";
  try {
    this[func]();
  }catch(err) {
    if( debug ) window.alert("Chyba: " + err.message);
    return true;
  }
  return false;
}




/**
 * Zobrazi na strance malej DIV s napisem "loading"
 */
function loadingAjax() {
  try {
    var bodyElm = document.getElementsByTagName('body'); // ziskani elementu body

    // div pro zobrazeni hlasky
    var div = document.createElement('div'); // vytvoreni elementu DIV
    var divIdName = 'divLoading'; // ID div elementu
    div.setAttribute('id',divIdName); // priradime novemu DIVu jeho ID
    div.innerHTML = ""; // v DIVu napiseme text
    div.style.textAlign = "center";
    div.style.fontSize = "10px";
    div.style.position = "absolute";
    div.style.top = "40%";
    div.style.left = "50%";
    div.style.marginLeft = "-125px";

    div.style.width = "150px";
    div.style.padding = "20px";
    div.style.backgroundColor = "#ffffff";
    div.style.border = "thin solid #000000";

    // obrazek pro loading
    var img = document.createElement('img');
    var imgIdName = 'imgLoading';
    var imgSrc = ajaxLoaderImage;
    img.setAttribute('id',imgIdName);
    img.setAttribute('src', imgSrc);
    img.setAttribute('title','Cancel'); // priradime novemu DIVu jeho ID
    img.style.cursor = "pointer";

    var br = document.createElement('br');

    var span = document.createElement('span');
    span.innerHTML = '<br />Kliknutím na obrázek<br />můžete akci zrušit.';


    bodyElm[0].appendChild(div); // pridame DIV do stranky
    div.appendChild(img);
    div.appendChild(br);
    div.appendChild(br);
    div.appendChild(span);
  }catch(err) {
    if( debug ) window.alert("Chyba: " + err.message);
    return false;
  }
}




/**
 * Handler pro ukonceni AJAXoveho pozadavku, pokud kliknul na ikonku nacitani
 */
function imgLoading_handler() {
  try {
    http.abort();
    unLoadAjax();
  }catch(err) {
    if( debug ) window.alert("Chyba: " + err.message);
    return false;
  }
}


/**
 * Odstrani ze stranky DIV s napisem "loading"
 */
function unLoadAjax() {
  try {
    var bodyElm = document.getElementsByTagName('body'); // ziskani elementu body
    var div = document.getElementById('divLoading');
    bodyElm[0].removeChild(div);
  }catch(err) {
    if( debug ) window.alert("Chyba: " + err.message);
    return false;
  }
}



