                                        /**
* @fileoverview Parses defined attributes of AJAX-enabled elements and creates HTTP GET request
* @author <a href="mailto:rdodd@bild.de">Ramon Dodd</a>
*/
/**
*
* .----.-----.-----.-----.
 /      \     \     \     \
|  \/    |     |   __L_____L__
|   |    |     |  (           \
|    \___/    /    \______/    |
|        \___/\___/\___/       |
 \      \     /               /
  |                        __/
   \_                   __/
    |        |         |
    |                  |
    | H T T P F I S T  |
   
  Fast Injection Snippet Templating 
*/
/**
* de
* @name de
* @namespace Main namespace object (empty)
*/
var de = de || {};
/**
* de.bild
* @name bild
* @memberOf de
* @namespace Sub namespace object (for BILD-related constants)
*/
de.bild = de.bild || {};
/**
 * de.bild.httpFist
 * @param {$jQuery} jQuery - the jQuery namespace
 * @name httpFist
 * @function
 * @memberOf de.bild
 * @namespace Parses defined attributes of AJAX-enabled elements and creates HTTP GET request
 */
de.bild.httpFist = (function($){
        // the separator character. used to split the variables
     var separator = ';',
 
  // if there's a consistent url path then let's save it to keep the server var smaller
  urlPrefix = '',
 
  // class of parent element of child ajax triggers
  contentparentClass = 'data-ajax-contentparent',
 
  // we pass the context (parent div of the response content) back to the function so that we can reattach events more quickly
  $context = null,
 
  badBrowser = $.browser.msie && $.browser.version.substr(0,1)<9,
 
  // will match the following pattern - abc=;abc123/_.&,-:;
  // Example of expected string: #url=;friends-list001.snip;target=;pdemo1;contentparent=;true;data=;html;callback=;klasdasdflkjdf;
  regEx = /([a-zA-Z]+)?=\;([\w\d\W\D\_\-\=\.:\/,\&]+)\;/g,
  dataType = 'html',
  $target = null;
    /**
     * getValue: extracts value from allowed object:attribute pairs
     * @param {Objekt} data - contains the object of the Event
     * @returns {String|Null}
     * @name getValue
     * @function
     * @memberOf de.bild.httpFist
     * @private
     */
      function getValue(obj){
    var $obj = $(obj),
  nodeName = obj.nodeName.toLowerCase(),
  value = null;
 
  // all allowed objects:attributes are stored here
        switch (nodeName) {
            case ('a') : value = $obj.attr('href'); break;
            case ('select') : value = $obj.find('option:selected').val(); break;
   case ('input') : value = $obj.val(); break;
        }
  return value;
   };
    /**
     * replaceContent: extracts value from allowed object:attribute pairs
     * @param {$Object} $target - jQuery object which will be replaced
     * @param {String} response - HTML from the server
     * @name replaceContent
     * @function
     * @memberOf de.bild.httpFist
     * @private
     */
    function replaceContent($target,response) {
        if (badBrowser) {
                var $temp = $('<div/>'),
                temp = $temp.get(0);
                temp.innerHTML = response;
                $target.replaceWith(temp.innerHTML);
        } else {
            $target.replaceWith(response);
        }
 };
   
    /**
     * parse: reads the attribute value of an object, parses it and assembles an HTTP Request.
     * Allowed objects [and their attributes]: a[href], select[options.value]
     * Takes one argument <strong>obj</strong> which is an object:
     * <ul>
     * <li>@property {object} <strong>obj</strong> The object with which the Event is bound</li>
     * <li>@property {replace} <strong>str</strong> Should the target be replaced instead of filled?</li>
     * <li>@property {$object} <strong>$target</strong> (optional) jQuery Object which represents the target for injected Ajax content</li>
     * <li>@property {string} <strong>url</strong> (optional) pass a url manually</li>
     * <li>@method {function} <strong>callback</strong> (optional) Function to be executed after a successful Ajax operation. It gets the scope of the original Element on which the Event was bound</li>
     * </ul>
     * @param {Objekt} data - contains the object of the Event (mandatory), a target jQuery object (optional) and a callback function (optional)
     * @returns {Bool} false
     * @name parse
     * @function
     * @memberOf de.bild.httpFist
     * @private
     */
      function parse(data){
     // temp obj to store matched values
            var temp = {},
   s = getValue(data.obj);
         // if a required attribute exists and we don't already have
   // a target and url then move on
         if (s && !data.url) {
             // everything after the hash
             s = s.substring(s.indexOf('#')+1,s.length);
            
             // match our params. match stores them in an array
            
             var m = s.match(regEx);
            
             if (!m) return false;
            
             // pull out the keys and values and store them in temp
             for (var i=0,j=m.length;i<j;i++) {
                 var o = m[i].replace(regEx,'$1'+separator+'$2').split(separator);
                 temp[o[0]]=o[1];
             } // endfor
             
         } // endif
        // make sure we have all the values we need
  // the id of the target element
        var target = (temp.target) ? temp.target : null,
  url = (data.url) ? data.url : urlPrefix + temp.url,
  hasTarget = false;
        //json?
        dataType = (data.dataType) ? data.dataType : 'html';
        // no url, no ajax
        if (!url) return false;
               
        if (target) {
      // let's jquery that id
      $target = $('#'+target);
            hasTarget = true;
        }
        // manual override: here, if a jquery object was passed to the function as $target, we want that to be the place where we inject the HTML
  // we will still pass whatever target we find in the url string as a parameter
  if (data.$target) {
   $target = data.$target;
   hasTarget = true;
  }
  $.ajax({
   'url': url,
   'dataType': dataType,
   'cache' : true,
   'timeout' : 5000,
   'success': function(response){
    if (hasTarget && $target.length) {
     if (data.replace) {
      $context = $target.parent();
      replaceContent($target,response);
     } else {
      $target.get(0).innerHTML = response;
      $context = $target;
     }
    }
    // let's give the callback the scope of the original object   
    (typeof data.callback === 'function') && data.callback.apply(data.obj,[response,$context]);
   },
   'error': function(){
    // what do we do here?
   }
  }); //ajax
 
  return false;
   };    
   // public Interface
    return {
    'load' : function(data){
        data && data.obj && parse(data);  
     }
   
    };
   
}(jQuery));

