dojo.require("dojo.hash");

/**
 * Asynchronously load html content from the server.
 * The response will be loaded from contentUrl and put inside the
 * div with id targetDiv. The innerHTML values of a div with class
 * 'xhrCb' may define a callback to execute after load using the
 * doCallback function.
 * @param contentUrl Url to load the content from
 * @param targetDiv Id of the div to put the content in
 * @param formToSend Name of the form to send additionally (optional)
 * @param createHistoryEntry Boolean indicating wether to create a browser
 * history entry or not (default: true)
 */
var lastHash = null;
function loadContent(contentUrl, targetDiv, formToSend, createHistoryEntry) {
  var xhrConfig = {
    url:contentUrl,
    handleAs:"text",
    timeout:0,
    preventCache:false,

    load: function(response, ioArgs) {
      dojo.byId(targetDiv).innerHTML = response;
      var scriptNodes = dojo.query(".xhrScript", targetDiv);
      if (scriptNodes[0]) {
        dojo.eval(scriptNodes[0].innerHTML);
      }
      var cbNodes = dojo.query(".xhrCb", targetDiv);
      if (cbNodes[0]) {
        doCallback(cbNodes[0].innerHTML, targetDiv);
      }
      return response;
    },

    error: function(response, ioArgs) {
      //console.error("HTTP status code: ", ioArgs.xhr.status);
      return response;
    }
  };
  // make sure that the form exists
  if (document.forms[formToSend]) {
    xhrConfig.form = formToSend;
  }

  // do the server call
  dojo.xhrGet(xhrConfig);

  // add a history entry
  if (createHistoryEntry !== false) {
    var hash = dojo.objectToQuery({
      url: contentUrl,
      target: targetDiv
    });
	// store for later reference
	lastHash = hash;
    dojo.hash(hash);
  }
}

/**
 * After load callbacks.
 */
function doCallback(str, targetDiv) {

  // callback definitions
  function obj() {

    // callback used after click on 'Das Programm Thematisch'
    this.afterIndex = function(targetDiv) {
      selectMainTab(1);
      scroll(0,0);
    }
    // callback used after click on 'Suche1, Suche2'
    this.afterSearch = function(targetDiv) {
      selectMainTab(1);
      var nodes = dojo.query(".xhrResult", targetDiv);
      if (nodes[0]) {
        var resultNode = nodes[0];
        if (resultNode) {
          if (resultNode.innerHTML == "error")
          {
            dojo.query("#content").addClass("searchResultNegative");
            dojo.query("#tabs .tab1 a").addClass("red");
          }
        }
      }
      scroll(0,0);
	  hobit.myHobit.updateAllDisplay();
    }
    // callback used after click on 'Das Programm Chronologisch'
    this.afterList = function(targetDiv) {
      selectMainTab(2);
      scroll(0,0);
	  hobit.myHobit.updateAllDisplay();
	  initEventList();
    }
    // callback used after click on 'Veranstalter...'
    this.afterHost = function(targetDiv) {
      selectMainTab(3);
      scroll(0,0);
    }
    // callback used after click on 'Kooperationen...'
    this.afterCoops = function(targetDiv) {
      selectMainTab(4);
      scroll(0,0);
    }
    // callback used after click on 'Externe Links'
    this.afterLinks = function(targetDiv) {
      selectMainTab(5);
      scroll(0,0);
    }
    // callback used after click on 'Hobit Magazin'
    this.afterMagazin = function(targetDiv) {
      selectMainTab(6);
      scroll(0,0);
      // change the magazin button to yellow
      dojo.query("#mainContentBottom .tab1 a").addClass("yellow");
    }
    // callback used after click on '... Hochschulen'
    this.afterHochschulen = function(targetDiv) {
      selectMainBottomTab(2);
      scroll(0,0);
    }
    // callback used after click on '... Firmen'
    this.afterFirmen = function(targetDiv) {
      selectMainTab(3);
      scroll(0,0);
    }
    // callback used after click on '... Arbeitsagentur'
    this.afterArbeitsagentur = function(targetDiv) {
      selectMainBottomTab(4);
      scroll(0,0);
    }
    // callback used after click on 'Stadt Darmstadt'
    this.afterDarmstadt = function(targetDiv) {
      selectLocationTab(1);
    }
    // callback used after click on 'Veranstaltungsort...'
    this.afterOrt = function(targetDiv) {
      selectLocationTab(2);
    }
    // callback used after click on 'Videos'
    this.afterVideo = function(targetDiv) {
      // display the first video
      var firstvideo = $("#firstvideo");
      displayVideo(0, firstvideo.attr("src"), firstvideo.attr("alt"), firstvideo.attr("width"), firstvideo.attr("height"));
    }
    // callback used after click on 'Bilder'
    this.afterBilder = function(targetDiv) {
      // create image gallery
      $("a[rel=hobit_gallery]").fancybox({
        'transitionIn' : 'none',
        'transitionOut' : 'none',
        'titlePosition' : 'over',
        'titleFormat' : function(title, currentArray, currentIndex, currentOpts) {
          return '<span id="fancybox-title-over">Bild ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
        }
      });
    }
  }

  // call the callback
  var func = new obj();
  func[str](targetDiv);
}

/**
 * Helper functions for dynamically changing the display.
 */
function selectMainTab(id) {
  dojo.query("#content").removeClass("searchResultNegative");
  dojo.query("#tabs div a").removeClass("active").removeClass("red");
  // change the magazin button back to white
  dojo.query("#mainContentBottom .tab1 a").removeClass("yellow");
  if (id > 0) {
    selectMainBottomTab(0);
    dojo.query("#tabs .tab"+id+" a").addClass("active");
  }
}
function selectMainBottomTab(id) {
  dojo.query("#mainContentBottom div a").removeClass("active");
  if (id > 0) {
    selectMainTab(0);
    dojo.query("#mainContentBottom .tab"+id+" a").addClass("active");
  }
}
function selectLocationTab(id) {
  dojo.query("#locationTabs div a").removeClass("active");
  dojo.query("#locationTabs .tab"+id+" a").addClass("active");
}

/**
 * Callback for navigation
 */
function handleHashChange(hash) {
  if (hash.length > 0 && hash != lastHash) {
    var memento = dojo.queryToObject(hash);
    loadContent(memento.url, memento.target);
  }
}

/**
 * Utility functions
 */
function gup(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function preload(imgObj,imgSrc) {
  if (document.images) {
    eval(imgObj+' = new Image()');
    eval(imgObj+'.src = "'+imgSrc+'"');
  }
}
