/*
 * Implementation of Batavi AJAX
 *
 */


function btv_Ajax() {

  this.requestMethod     = 'post';
  this.requestParameters =  null;
  this.overlayBoxId      = 'boxOverlay';
  this.overlayId         = 'overlayShading';
  this.overlayInnerId    = 'boxOverlayInner';
  this.overlayImageId    = 'overlayIntermediateImage';
  this.overlayCSS        = 'overlayShading';
  this.overlayBoxCSS     = 'overlayBox';
  this.overlayBoxTop     = false;
  this.overlayBoxLeft    = false;
  this.intermediateImage = 'images/default/dynamic/ajax/ajax-loader.gif';
  this.isIE6             = false;
  this.overlayScriptBoxTop = 0;

  var tempImage          = new Image();
  tempImage.src          = this.intermediateImage;

  this.defaultOverlayHeight = 'auto';
  this.defaultOverlayWidth  = '600px';
  this.showEffectDuration   = 0.5;
  this.animationHeight      = '62px';
  this.animationWidth       = '80px';
  this.overlayOpacity       =  0.5;
  this.overlayDuration      =  0.5;

  var requestStarted     = false;
  var requestParameters  = '';
  this.showOverlay       = false;

  this.onBoxLoaded      = function() {
  }
  this.onOverlayHidden  = function(isClicked) {
  }
 /*
  * Function that loads single box
  *
  */

  this.loadBox = function(boxCode, boxInstance, intermediateImage, overlayWidth, overlayHeight, boxParameters, form) {
    if (intermediateImage != undefined || intermediateImage != null) {
      this.intermediateImage = intermediateImage;
    }
    this.overlayWidth      = overlayWidth;
    this.overlayHeight     = overlayHeight;
    var re  = /\?(.+)$/g;
    var re2 = /\&(.+)$/g;
    var old_query_str      = window.location.href.match(re);
    requestParameters = {box: boxCode, box_instance: boxInstance || ''};
    if (this.requestParameters != undefined) {
      for (k in this.requestParameters) {
        if (this.requestParameters[k] == undefined) {
          this.requestParameters[k] = '';
        }
        requestParameters[k] = this.requestParameters[k];
      }
      this.requestParameters = null;
    }

    var query_str = old_query_str;
    if (query_str != undefined) {
      requestParameters['query_string'] = query_str.slice(1, query_str.length);
    } else {
      requestParameters['query_string'] = '';
    }

    if (old_query_str != undefined) {
      requestParameters['old_query_str'] = old_query_str;
    } else {
      requestParameters['old_query_str'] = '';
    }
    if (window.location.href != '') {
      requestParameters['window_location_href'] = window.location.href;
    }
    for (k in boxParameters) {
      if (boxParameters[k] == undefined) {
        boxParameters[k] = '';
      }
      requestParameters[k] = boxParameters[k];
    }
    if (form != undefined) {
      var formParameters = $(form).serialize(true);
      for (k in formParameters) {
        if (formParameters[k] == undefined) {
          formParameters[k] = '';
        }
        requestParameters[k] = formParameters[k];
      }
      if ($(form).action != undefined) {
        if ($(form).action != '') {
            requestParameters['form_action'] = $(form).action;
        }
        actionParameters = $(form).action.match(re2);
        actionParameters_str = '';
        k = 1;
        var str = new String(actionParameters);
        for (i=0; i<str.length; i++) {
          if (str.charAt(i) == '/') {
            if (k == 1) {
              actionParameters_str += '=';
            } else {
              actionParameters_str += '&';
            }
            k = -k;
          } else {
            actionParameters_str += str.charAt(i);
          }
        }

        actionParameters = actionParameters_str.toQueryParams();
        for (k in actionParameters) {
          if (actionParameters[k] == undefined) {
            actionParameters[k] = '';
          }
          requestParameters[k] = actionParameters[k];
        }
      }
    }
    this.showOverlay            = true;
    return this.request();
  }

 /*
  * Function that sends request to server
  *
  */

  this.request = function() {
    if (requestStarted == false) {
      requestStarted = true;
      this.animationStart();
      new Ajax.Request('ajax.php',
      {
        method:     this.requestMethod,
        parameters: requestParameters,
        onSuccess:  this.success(this),
        onFailure:  this.failure(this)
      });
      return true;
    } else {
      return false;
    }
  }

 /*
  * Function for ajax onsuccess event. Shows rendered box
  *
  */

  this.success = function(obj) {
    return function(transport) {
      if (transport.responseText != '' && obj.showOverlay) {
        if (transport.responseText.indexOf('[[0|stop_rendering]]') != -1) {
          var scripts = transport.responseText.extractScripts();
          for (var i = 0; i < scripts.length; i++) {
            window.eval(scripts[i]);
          }
          return false;
        }
        obj.animationStop();
        obj.overlayShow();
        var overlayBox          = $(obj.overlayBoxId);
        overlayBox.style.visibility = 'hidden';

        oldOverlayBoxWH         = $(overlayBox).getDimensions();
        if (obj.isIE6) {
          oldPositionTop        = obj.overlayScriptBoxTop;
        } else {
          oldPositionTop        = overlayBox.style.top;
        }
        oldPositionLeft         = overlayBox.style.left;

        if (obj.isIE6) {
          this.overlayScriptBoxTop    = '0px';
        } else {
          overlayBox.style.top    = '0px';
        }
        overlayBox.style.left   = '0px';
        overlayBox.style.height = obj.overlayHeight;
        overlayBox.style.width  = obj.overlayWidth;

        obj.overlayBoxInner.innerHTML    = transport.responseText;
        overlayBoxWH            = $(overlayBox).getDimensions();
        var windowWH            = $(document.body).getDimensions();
        //back to center of screen
        if (obj.isIE6) {
          obj.overlayScriptBoxTop    = oldPositionTop;
        } else {
          overlayBox.style.top    = oldPositionTop;
        }
        overlayBox.style.left   = oldPositionLeft;
        overlayBox.style.height = oldOverlayBoxWH.height + 'px';
        overlayBox.style.width  = oldOverlayBoxWH.width + 'px';
        obj.overlayBoxInner.innerHTML = '&nbsp;';

        var newTop;
        var newLeft;
        if (obj.overlayBoxTop == false) {
          newTop  = Math.round((document.documentElement.clientHeight - overlayBoxWH.height)/2);
        } else {
          newTop  = obj.overlayBoxTop;
        }
        if (obj.overlayBoxLeft == false) {
          newLeft = Math.round((document.documentElement.clientWidth - overlayBoxWH.width)/2);
        } else {
          newLeft = obj.overlayBoxLeft;
        }
        var childrens = overlayBox.immediateDescendants();
        if (childrens != undefined && childrens.length >0) {
          for (var i = 0; i < childrens.length; i++) {
            childrens[i].hide();
          }
        }
        overlayBox.style.visibility = 'visible';

        if (!obj.isIE6) {
          overlayBox.morph('top:' + newTop + 'px;left: ' + newLeft + 'px;height:' + overlayBoxWH.height + 'px;width:' + overlayBoxWH.width + 'px',{
            duration: obj.showEffectDuration,
            afterFinish: function(o) {
                var overlayBox  = $(obj.overlayBoxId);
                var childrens = overlayBox.immediateDescendants();
                if (childrens != undefined && childrens.length >0) {
                  for (var i = 0; i < childrens.length; i++) {
                    childrens[i].show();
                  }
                }
                obj.overlayBoxInner.innerHTML = transport.responseText;
                var scripts = transport.responseText.extractScripts();
                for (var i = 0; i < scripts.length; i++) {
                  window.eval(scripts[i]);
                }
                obj.onBoxLoaded();
                obj.onBoxLoaded = function() {
                }
                requestStarted = false;
           }});
        } else {
          obj.overlayScriptBoxTop = newTop;
          var overlayBox          = $(obj.overlayBoxId);
          overlayBox.style.left   = newLeft;
          overlayBox.style.height = overlayBoxWH.height + 'px';
          overlayBox.style.width  = overlayBoxWH.width + 'px';
          var childrens = overlayBox.immediateDescendants();
          if (childrens != undefined && childrens.length >0) {
            for (var i = 0; i < childrens.length; i++) {
              childrens[i].show();
            }
          }
          obj.overlayBoxInner.innerHTML = transport.responseText;
          var scripts = transport.responseText.extractScripts();
          for (var i = 0; i < scripts.length; i++) {
            window.eval(scripts[i]);
          }
          obj.onBoxLoaded();
          obj.onBoxLoaded = function() {
          }
          requestStarted = false;
        }
      } else {
        obj.animationStop();
        obj.overlayHide();
        requestStarted = false;
      }


    }
  }

 /*
  * Function for ajax onfailure event
  *
  */

  this.failure = function(obj) {
    return function(transport) {
      requestStarted = false;
      obj.animationStop();
      obj.overlayHide();
    }
  }

 /*
  * Function that shows overlay with animation
  *
  */

  this.animationStart = function() {
    if (this.showOverlay) {
      var overlay    = $(this.overlayId);
      var overlayBox = $(this.overlayBoxId);
      if ((overlay == undefined) || (overlayBox == undefined)) {
        this.overlayCreate();
        overlay    = $(this.overlayId)
        overlayBox = $(this.overlayBoxId);
      } else {
        Event.observe(this.overlayId, 'click', (function(event) {
          var element = Event.element(event);
          if (this.overlayId == element.id) {
            if (requestStarted == false) {
              this.overlayHide(true);
            }
          }
        }).bindAsEventListener(this));
      }

      if (this.detectIE6()) {
        this.isIE6 = true;
        overlay.style.position = 'absolute';
        if (overlayBox != undefined) {
          overlayBox.style.position = 'absolute';
        }
      }

      if (overlayBox != undefined) {
        var overlayChilds = overlayBox.descendants();
        if (overlayChilds != undefined && overlayChilds.length > 0 && $(this.overlayInnerId) == undefined) {
          this.overlayBoxInner = overlayChilds[(overlayChilds.length - 1)];
          this.overlayBoxInner.setAttribute('id', this.overlayInnerId);
          this.overlayBoxInner.id = this.overlayInnerId;
        } else if ($(this.overlayInnerId) != undefined) {
          this.overlayBoxInner = $(this.overlayInnerId);
        } else {
          this.overlayBoxInner = overlayBox;
          this.overlayInnerId  = this.overlayInnerId;
        }
      }
      if (overlayBox != undefined) {
        this.overlayBoxInner.innerHTML    = '';
        if (this.intermediateImage != '') {
          this.overlayShow();
          overlayBox.style.visibility = 'hidden';
          overlay.className       = this.overlayCSS;
          overlayBox.className    = this.overlayBoxCSS;
          if (this.isIE6) {
            this.overlayScriptBoxTop = 0;
          } else {
            overlayBox.style.top    = '0px';
          }
          overlayBox.style.left   = '0px';
          overlayBox.style.height = this.animationHeight;
          overlayBox.style.width  = this.animationWidth;

          var image = document.createElement('img');
          image.setAttribute('id', this.overlayImageId);
          image.src = this.intermediateImage;
          overlayBox.appendChild(image);
          var imageWH             = $(image).getDimensions();
          var overlayBoxWH        = $(this.overlayBoxId).getDimensions();
          var overlayBoxInnerWH   = this.overlayBoxInner.getDimensions();
          image.style.position    = 'absolute';
          overlayBox.style.height = overlayBoxWH.height + 'px';
          overlayBox.style.width  = overlayBoxWH.width + 'px';
          var windowWH            = $(document.body).getDimensions();
          if (this.overlayBoxTop == false) {
            if (this.isIE6) {
              this.overlayScriptBoxTop  = Math.round((document.documentElement.clientHeight - overlayBoxWH.height)/2) + 'px';
            } else {
              overlayBox.style.top  = Math.round((windowWH.height - overlayBoxWH.height)/2) + 'px';
            }
          } else {
            if (this.isIE6) {
              this.overlayScriptBoxTop  = this.overlayBoxTop;
            } else {
              overlayBox.style.top  = this.overlayBoxTop;
            }
          }
          if (this.overlayBoxLeft == false) {
            overlayBox.style.left = Math.round((document.documentElement.clientWidth - overlayBoxWH.width)/2) + 'px';
          } else {
            overlayBox.style.left = this.overlayBoxLeft;
          }
          image.style.top       = Math.round((overlayBoxWH.height - imageWH.height)/2) + 'px';
          image.style.left      = Math.round((overlayBoxWH.width - imageWH.width)/2) + 'px';
          overlayBox.style.visibility = 'visible';
          //this.overlayScriptBoxTop = overlayBox.style.top;
        }
        return true;
      }
    }
    return false;
  }

 /*
  * Function that hides animation when box loaded
  *
  */

  this.animationStop = function() {
    var image = $(this.overlayImageId);
    if (image != undefined) {
      image.remove();
    }
    if (this.overlayBoxInner != undefined) {
      this.overlayBoxInner.innerHTML = '';
      return true;
    }
    return false;
  }

 /*
  * Function to create overlay
  *
  */

  this.overlayCreate = function() {
    overlay    = document.createElement('div');
    overlay.setAttribute('id', this.overlayId);
    overlay.className = this.overlayCSS;
    overlayBox = document.createElement('div');
    overlayBox.setAttribute('id', this.overlayBoxId);
    overlayBox.className = this.overlayBoxCSS;
    overlayBox.style.height = this.overlayHeight;
    overlayBox.style.width = this.overlayWidth;
    document.body.appendChild(overlayBox);
    document.body.appendChild(overlay);
    Event.observe(this.overlayId, 'click', (function(event) {
      var element = Event.element(event);
      if (this.overlayId == element.id) {
        if (requestStarted == false) {
          this.overlayHide(true);
        }
      }
    }).bindAsEventListener(this));
    this.overlayHide();
  }

 /*
  * Function that shows overlay
  *
  */

  this.overlayShow = function() {
    if ($(this.overlayId) != undefined) {
      if ($(this.overlayId).style.display == 'none') {
        $(this.overlayId).style.opacity = 0;
        $(this.overlayId).show();
        new Effect.Opacity(this.overlayId, { from: 0, to: this.overlayOpacity, duration: this.overlayDuration });
      }
    }
    if ($(this.overlayBoxId) != undefined) {
      $(this.overlayBoxId).show();
    }
  }

 /*
  * Function that hides overlay
  *
  */

  this.overlayHide = function(clicked) {
    if ($(this.overlayId) != undefined) {
      $(this.overlayId).hide();
    }
    if ($(this.overlayBoxId) != undefined) {
      $(this.overlayBoxId).hide();
    }
    if (window.messageTimer != undefined) {
      window.clearTimeout(window.messageTimer);
      window.messageTimer = undefined;
    }
    if (clicked != undefined) {
      this.onOverlayHidden(true);
    } else {
      this.onOverlayHidden(false);
    }
    this.onOverlayHidden = function(isClicked) {
    }
    if (this.overlayBoxInner != undefined) {
      this.overlayBoxInner.innerHTML = '';
    }
  }

 /*
  * Home made unescape method
  */

  this.unescapeHTML = function (html) {
    var htmlNode = document.createElement("DIV");
    html = html.replace(/&nbsp;/g, "FDTUdvsadauiFWTDEE83oe87342"); //some unique keyword
    htmlNode.innerHTML = html;
    if(htmlNode.innerText) {
      var s = htmlNode.innerText.replace(/FDTUdvsadauiFWTDEE83oe87342/g, "&nbsp;"); // IE
      var prev = "";
      do {
        prev = s;
        s = s.replace(/\<\/(.+)\>\<\/(.+)\>/g, "</$1> </$2>");
      } while (s != prev);
      return s;
    }
    return htmlNode.textContent.replace(/FDTUdvsadauiFWTDEE83oe87342/g, "&nbsp;"); // FF
  }

  /********************************************************** OVERLAYS IMPLEMENTATION **********************************************************/
  /*
   * Implementation of action/message overlay
   */

  this.fireAction = function (action, parameters, boxToReload, width, height, form) {

    var overlayWidth  = (typeof width  == "undefined" || width == '') ? this.defaultOverlayWidth : width;
    var overlayHeight = (typeof height == "undefined" || height == '') ? this.defaultOverlayHeight : height;

    var requestForm, reloadBox;
    if (form != undefined) {
      requestForm = form;
    }

    if (boxToReload != undefined) {
      reloadBox = boxToReload;
    }

    var boxParameters = {
                      action:             action,
                      boxToReload:        reloadBox,
                      parameters:         parameters
                    };

    for(i = 6; i < this.fireAction.arguments.length; i = i + 2) {
    	boxParameters[this.fireAction.arguments[i]] = this.fireAction.arguments[i + 1];
    }

    this.loadBox('boxMessagesUser', 'general', null, overlayWidth, overlayHeight, boxParameters, requestForm);

    return false;

  }

  /*
   * Implementation of product images overlay
   */

  this.showProductImages = function (productID, selectedImageID, scrollIndex, imagesLimit, currentIndex, width, height) {

    overlayWidth  = (typeof width  == "undefined") ? '600px' : width;
    overlayHeight = (typeof height == "undefined") ? 'auto' : height;

    if ((selectedImageID == '') && (document.getElementById('box_product_details_image_thumb') != undefined)) {
      var re = /(url\()(.*)(\))/g;
      var str = document.getElementById('box_product_details_image_thumb').style.backgroundImage;
      var matches = str.match(re);
      if ((RegExp != undefined) && (RegExp.$2 != undefined)) {
        selectedImageID = RegExp.$2;
      }
    }


    this.loadBox('boxProductImages', 'general', null, overlayWidth, overlayHeight,
                  {
                    products_id       : productID,
                    selected_image_id : selectedImageID,
                    scroll_index      : scrollIndex  || 0,
                    images_limit      : imagesLimit  || 0,
                    current_index     : currentIndex || 0
                  });

    return false;
  }

  /*
   * Implementation of product stock information overlay
   */

  this.showProductStock = function (productID, width, height) {

    overlayWidth  = (typeof width  == "undefined") ? '544px' : width;
    overlayHeight = (typeof height == "undefined") ? 'auto' : height;

    this.loadBox('boxProductStock', 'general', null, overlayWidth, overlayHeight,
                  {
                    products_id:       productID
                  });

    return false;
  }
  
  this.showAccountAddress = function (addressType, orderId, width, height) {
    overlayWidth  = (typeof width  == "undefined") ? '544px' : width;
    overlayHeight = (typeof height == "undefined") ? 'auto' : height;

    this.loadBox('boxAccountAddress', 'general', null, overlayWidth, overlayHeight,
              {
                orderId    :       orderId,
                addressType:       addressType
              });

    return false;
  }
  /*
   * Implementation of product delivery information overlay
   */

  this.showProductShipping = function (productID, width, height) {

    overlayWidth  = (typeof width  == "undefined") ? '544px' : width;
    overlayHeight = (typeof height == "undefined") ? 'auto' : height;

    this.loadBox('boxProductShipping', 'general', null, overlayWidth, overlayHeight,
                  {
                    products_id:       productID
                  });

    return false;
  }

  /*
   * Implementation of boxTellaFriend overlay
   */

  this.showTellaFriend = function (productID, width, height, param) {

    overlayWidth  = (typeof width  == "undefined") ? '566px' : width;
    overlayHeight = (typeof height == "undefined") ? 'auto' : height;
    var reqParams = {process: 'boxTellaFriend', product_id: productID};
    if (param != undefined) {
      for (k in param) {
        reqParams[k] = param[k];
      }
    }
    this.loadBox('boxTellaFriend', 'general', null, overlayWidth, overlayHeight, reqParams);

    return false;
  }

  /*
   * Implementation of password forgotten overlay
   */
  this.showPasswordForgotten = function (width, height, param) {
    overlayWidth  = (typeof width  == "undefined") ? '575px' : width;
    overlayHeight = (typeof height == "undefined") ? 'auto' : height;

    this.loadBox('boxPasswordForgotten', 'general', null, overlayWidth, overlayHeight, param);

    return false;
  }

  /**
   * showModule
   *
   * @param width
   *
   * @param height
   *
   * @param param
   */
  this.showModule = function (set_module, set_method, height, width){
    overlayWidth  = (typeof width  == "undefined") ? '600px' : width;
    overlayHeight = (typeof height == "undefined") ? 'auto'  : height;

    this.loadBox('boxModuleOptions', 'general', null, overlayWidth, overlayHeight,
                  {module : set_module,
                   method : set_method}
                );

    return false;
  }

  /*
   * Implementation of account address edit overlay
   */
  this.showAccountAddressEdit = function (param, width, height) {
    overlayWidth  = (typeof width  == "undefined") ? '600px' : width;
    overlayHeight = (typeof height == "undefined") ? 'auto' : height;

    this.loadBox('boxAccountAddressEdit', 'general', null, overlayWidth, overlayHeight, param);

    return false;
  }

  /*
   * Implementation of cart address edit overlay
   */
  this.showCartAddressEdit = function (param, width, height) {
    overlayWidth  = (typeof width  == "undefined") ? '600px' : width;
    overlayHeight = (typeof height == "undefined") ? 'auto' : height;

    this.loadBox('boxCartAddressEdit', 'general', null, overlayWidth, overlayHeight, param);

    return false;
  }

  /*
   * Implementation of cart address book overlay
   */
  this.showCartAddressBook = function (param, width, height) {
    overlayWidth  = (typeof width  == "undefined") ? '600px' : width;
    overlayHeight = (typeof height == "undefined") ? 'auto' : height;

    this.loadBox('boxCartAddressBook', 'general', null, overlayWidth, overlayHeight, param);

    return false;
  }

  /*
   * Implementation of custom message overlay
   */
  this.btv_Alert = function (message, type, width, height) {
    overlayWidth  = (typeof width  == "undefined") ? '600px' : width;
    overlayHeight = (typeof height == "undefined") ? 'auto'  : height;
    messageType   = (typeof type == "undefined")   ? 'error' : type;


    this.loadBox('boxMessagesUser', 'general', null, overlayWidth, overlayHeight,
                  {
                    message: message,
                    type:    messageType
                  }, null);

    return false;

    }

  /*
   * Implementation  cart shipping overlay
   */

  this.showCartShippingOverlay = function (width, height) {

    overlayWidth  = (typeof width  == "undefined") ? '544px' : width;
    overlayHeight = (typeof height == "undefined") ? 'auto' : height;

    this.loadBox('boxCartShippingOverlay', 'general', null, overlayWidth, overlayHeight);

    return false;
  }

  /*
   * Function for detecting IE6
   */

  this.detectIE6 = function() {
    var browser = navigator.appName;
      if (browser == "Microsoft Internet Explorer"){
        var b_version = navigator.appVersion;
        var re = /\MSIE\s+(\d\.\d\b)/;
        var res = b_version.match(re);
        if (res[1] <= 6){
          return true;
        }
      }
      return false;
  }

}


/*
 * Make the object be globally accessible
 */

var ajax = new btv_Ajax();

function getOverlayTop() {
  if ((ajax != undefined) && ajax.isIE6) {
    return ((document.documentElement && document.documentElement.scrollTop) ? parseInt(document.documentElement.scrollTop) : document.body.scrollTop ? parseInt(document.body.scrollTop) : 0 ) + 'px';
  } else {
    return false;
  }
}

function getOverlayBoxTop() {
  if ((ajax != undefined) && ajax.isIE6) {
    //alert((((document.documentElement && document.documentElement.scrollTop) ? parseInt(document.documentElement.scrollTop) : document.body.scrollTop ? parseInt(document.body.scrollTop) : 0 ) + parseInt(ajax.overlayScriptBoxTop)) + 'px');
    return (((document.documentElement && document.documentElement.scrollTop) ? parseInt(document.documentElement.scrollTop) : document.body.scrollTop ? parseInt(document.body.scrollTop) : 0 ) + parseInt(ajax.overlayScriptBoxTop)) + 'px';
  } else {
    return ajax.overlayScriptBoxTop + 'px';
  }
}
