/**
 *
 */
/**
 *
 */
var HistoryManager = {
  hashCheck : null,
  currentHash : null,

  init : function(options) {
    this.currentHash = window.location.hash;
    this.hashCheck = setInterval(function() {
      HistoryManager.checkHash();
    }, 50);
    this.settings = {
      onUrlUpdate : function(hash) {
      },
      onUrlUpdateError : function(error) {
      }
    };

    for ( var i in options) {
      this.settings[i] = options[i];
    }
    if (this.currentHash) {
      this.settings.onUrlUpdate
          .call(self, this.getHashString(this.currentHash));
      this.setUserReferer();
    }
  },

  /**
   * This function tracks the change in URL. It keeps running every 50ms.
   */

  checkHash : function() {
    if (window.location.hash != this.currentHash) {
      this.currentHash = window.location.hash;
      this.pageChange(HistoryManager.getHashString(this.currentHash));
    }
  },

  /**
   * This function will return the hash part of the URL
   *
   * @param {string}
   * This is hash URL
   */

  getHashString : function(hash) {
    return hash.substr(1, hash.length);
  },

  /**
   * This function gets fired when ever there is change in URL
   *
   * @param {string}
   */

  pageChange : function(hash) {
    this.settings.onUrlUpdate.call(self, hash);
    this.setUserReferer();
  },

  /**
   * This function returns the value of parameter passed to it
   *
   * @param {string}
   *          This is the name of parameter whose value will be returned
   * @param {string}
   *          This is URL
   */

  getQueryStringParameter : function(paramName, url) {
    /*
     * if (arguments.length<2) { this.settings.onUrlUpdateError.call(self,
     * "Missing or invalid argument"); }
     */
    var i, len, idx, queryString, params, tokens;

    url = url || window.location.href;

    idx = url.indexOf("?");
    queryString = idx >= 0 ? url.substr(idx + 1) : url;

    // Remove the hash if any
  idx = queryString.lastIndexOf("#");
  queryString = idx >= 0 ? queryString.substr(0, idx) : queryString;

  params = queryString.split("&");

  for (i = 0, len = params.length; i < len; i++) {
    tokens = params[i].split("=");
    if (tokens.length >= 2) {
      if (tokens[0] === paramName) {
        return unescape(tokens[1]);
      }
    }
  }
  return null;
},

/**
 * This function sets the hash URL. Multiple parameters can also be set e.g.
 * HistoryManager.setHash('param1':value1, 'param2':value2) *
 *
 * @param {object}
 *          states Associative array of parameter-state pairs to set
 *          simultaneously
 */

setHash : function(states) {
  var currentStates = [], newHash;
  if (typeof states !== "object") {
    this.settings.onUrlUpdateError.call(self, "Missing or invalid argument");
  }

  for (state in states) {
    currentStates.push(state + "=" + states[state]);
  }
  newHash = currentStates.join("&");
  this.currentHash = newHash;
  window.location.hash = newHash;
},

/**
 * This function returns the value of the parameter passed to it. If not given
 * the second parameter it takes the URL location and does the processing.
 *
 * @param {string}
 *          Its the name of the parameter the value which you would like to get
 * @param {string}
 *          Its optional. Its the hash string.
 */

getParamValue : function(paramType, urlHash) {
  if (!urlHash) {
    urlHash = window.location.hash;
  }
  if (urlHash.lastIndexOf('#') == 0) {
    urlHash = HistoryManager.getHashString(urlHash);
  }
  return HistoryManager.getQueryStringParameter(paramType, urlHash);
},

/**
 * This function send request to set the referer, every time url has change
 * replace '?' and '&' with '!~!' and '!*!' respectively, to send the complete
 * url as string
 */
setUserReferer : function() {
  var currentURL = window.location.href;

  currentURL = currentURL.replace("#", "!~!");
  var myRegExp = new RegExp("&", "g");
  currentURL = currentURL.replace(myRegExp, "!*!");

  new Ajax.Updater('', $('user_referer').href, {
    method : 'post',
    parameters : 'redirect_to=' + currentURL
  });

}
};

/* ---------------- Start common JS */
var RC = {

  messageObj : 'message_box',
  hideClass: 'hide',
  activeClass: 'active',
  disabledClass: 'disabled',
  selectedClass: 'selected',

  init : function() {
    this.loadingObj = $('ajax_working');
    this.requestErrorMessage = 'Oops, something went wrong, please reload the page and try again.';
  },

  onFailure : function(request) {
    alert(this.requestErrorMessage);
  },

  isRequesting : function(opt, obj) {
    var opac = 1;
    if (opt) {
      this.loadingObj.show();
      opac = 0.3;
    } else {
      this.loadingObj.hide();
    }
    if (obj)
      obj.setOpacity(opac);
  },

  setMaxLen : function(obj, maxLen) {
    obj.observe('keypress', function(event) {
      if (this.value.length > maxLen)
        event.stop();
      this.value = this.value.substring(0, maxLen);
    });
    obj.observe('keyup', function(event) {
      if (this.value.length > maxLen)
        this.value = this.value.substring(0, maxLen);
    });
    obj.observe('blur', function() {
      if (this.value.length > maxLen)
        this.value = this.value.substring(0, maxLen);
    });
  },

  setMessage : function(message, container, type, autoremove) {
    this.removeMessage();

    var str = "";
    if (message.isJSON()) {
      var message = message.evalJSON(true);
      for (key in message) {
        str += '<div>' + message[key] + '</div>';
      }
    } else {
      str = message;
    }
    str = '<div id="'
        + this.messageObj
        + '"><a href="#" onclick="RC.removeMessage();return false;">X</a><div>'
        + str + '</div></div>';

    Element.insert(container, {
      top : str
    });
    if(type) {
      $(this.messageObj).addClassName(type);
    }
    $(this.messageObj).scrollTo();
    
    if (autoremove) {
      setTimeout(function() {RC.removeMessage()}, 4000);
    }
  },

  removeMessage : function() {
    if ($(this.messageObj))
      $(this.messageObj).remove();
  },
  
  trim: function (str)
  {
    if(!str || typeof str != 'string')
      return null;
    else
      return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
  },
  
  isValidEmail: function (value) {
    var email  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return value.match(email);       
  },
  

  toggleInlinePopup : function(element, parent) {
    var elementDim = Element.getDimensions(element);
    var viewportDim = document.viewport.getDimensions();
    var scOffset = document.viewport.getScrollOffsets(); // get scroll

    var topVal = ((viewportDim.height - elementDim.height) / 2) + scOffset[1];
    // minimize the top position
   // topVal -= 50;
  //  topVal = topVal < 50 ? 50 : topVal;

    var leftVal = ((viewportDim.width - elementDim.width) / 2) + scOffset[0];

    if(parent) {
      var containerOffset = parent.cumulativeOffset();
      var containerDim = parent.getDimensions();
      leftVal = (containerOffset.left + ((containerDim.width - elementDim.width) / 2)) ;
    }
    element.style.top =  topVal + 'px';
    element.style.left =  leftVal + 'px';
  },
  
  setToolTip : function(toolTip, opt, thisObj) {
    if (opt == false) {
      toolTip.updater = null;
      toolTip.addClassName(this.hideClass);
    } else {
      toolTip.updater = thisObj;
      var offset      = thisObj.cumulativeOffset(); // get hover object offset
      var vOffset     = thisObj.viewportOffset(); // get viewport offset dimension
      var vDimension  = document.viewport.getDimensions(); // get viewport
      var scOffset    = document.viewport.getScrollOffsets(); // get scroll
      
      var bottomClass = 'bottom';

      toolTip.removeClassName(this.hideClass);
      toolTip.removeClassName(bottomClass);
     
      var topVal = offset[1] + 28;
      var diff   = topVal - ((vDimension.height - toolTip.getHeight()) + scOffset[1]);

      if (diff > 0) {
        topVal = topVal - (toolTip.getHeight() + 25);
        toolTip.addClassName(bottomClass);
      } 
      toolTip.setStyle( {
        top : topVal + 'px',
        left : offset[0] + 'px'
      });
    }
  },
  
  /**
   * get drop menu buttons
   * @returns Objects Array
   */
  getDropmenuButtons: function(container) {
    if (!container.menuButtons) {
      container.menuButtons = container.select('.default-button');
    }
    return container.menuButtons;
  },
  
  /**
   * get menu object for each dropmenu button
   * @param thisObj button object
   * @returns Object
   */
  getDropmenuSection : function(thisObj) {
    return thisObj.up().section;
  },
  
  /**
   * show custom drop menu
   */
  showDropmenu : function(thisObj) {
    var section = this.getDropmenuSection(thisObj);
    var position = thisObj.positionedOffset().left;
    setTimeout(function() {
      section.removeClassName(RC.hideClass);
      section.style.left = position + 'px';
    }, 200);
  },

  /**
   * hide custom drop menu
   */
  hideDropmenu : function(thisObj) {
    var section = this.getDropmenuSection(thisObj);
    setTimeout(function() {
      section.addClassName(RC.hideClass);
    }, 200);
  }
};

RC.AJAX = Class.create();

RC.AJAX.prototype = {

  initialize : function() {

  },

  setForm : function(form, options) {
    form.stopObserving();
    form.observe('submit', function(event) {
      event.stop();
      new RC.AJAX.form(this, options);
    });
  },

  // Merge the users options with default settings
  setUserSettings : function(settings, options) {
    for ( var i in options) {
      settings[i] = options[i];
    }
    return settings;
  }
};

RC.AJAX.sendQuery = Class.create();
RC.AJAX.sendQuery.prototype = {
  initialize : function(updater, url, thisObj, options) {
    var obj = this;
    this.settings = {
      params : false,
      method : 'get',
      onComplete : function(request, updater, thisObj) {
      },
      onFailure : function(request) {
        RC.onFailure(request);
      }
    };

    var setObj = new RC.AJAX();
    this.settings = setObj.setUserSettings(this.settings, options);

    RC.isRequesting(true, updater);
    new Ajax.Updater(updater, url, {
      method : this.settings.method,
      parameters : this.settings.params,
      onComplete : function(request) {
        obj.onComplete(request, updater, thisObj);
      }
    });
  },

  /**
   * This is callback function, which call afer completion of request.
   *
   * @param request
   * @param updater
   *          element, which need to be updated with response content
   * @param action
   *          element
   */
  onComplete : function(request, updater, thisObj) {
    RC.isRequesting(false, updater);
    if (request.status == 200)
      this.settings.onComplete.call(self, request, updater, thisObj);
    else
      this.settings.onFailure.call(self, request);

  }
};

RC.AJAX.form = Class.create();
RC.AJAX.form.prototype = {

  initialize : function(form, options) {
    this.settings = {
      onSubmit: function(form) {      
      }, 
      onComplete: function(request, form) {
      },
      onFailure: function(request) {
        RC.onFailure(request);
      }
    };
    /*
     * Overwrite the default settings
     */
    var setObj = new RC.AJAX();
    this.settings = setObj.setUserSettings(this.settings, options);

    var obj = this;
    RC.removeMessage();
    form.request( {
      parameters : Form.serialize(form),
      onLoading : obj.onSubmit(form),
      onComplete : function(request) {
        obj.onComplete(request, form);
      }
    });
  },

  onSubmit : function(form) {
    RC.isRequesting(true, form);
    form.disable();
    this.settings.onSubmit.call(self, form);
  },

  onComplete : function(request, form) {
    form.enable();
    RC.isRequesting(false, form);
    if (request.status == 200)
      this.settings.onComplete.call(self, request, form);
    else
      this.settings.onFailure.call(self, request);
  }

};

/*------------ Modal Popup JS -----------*/

var RC_POPUP = {

  RC_Overlay : 'RC_overlay',
  RC_Frame : 'modal_content',
  hideClass : 'hide',
  _init : false,
  _is_active : false,

  init : function() {
    if (!$(this.RC_Overlay)) {
      var overlay = document.createElement("div");
      overlay.id = this.RC_Overlay;
      document.body.insertBefore(overlay, document.body.childNodes[0]);

      // this.RC_Overlay = $(this.RC_Overlay);
  $(this.RC_Overlay).observe("click", function() {
    RC_POPUP.hide();
  });
}
if (!this._init) {
  Event.observe(document, "keypress", function(event) {
    if ((event.keyCode == Event.KEY_ESC) && (RC_POPUP._is_active)) {
      RC_POPUP.hide();
    }
  });
  this._init = true;
}
},

  show : function() {
    this.init();

    $(this.RC_Overlay).setOpacity(0.6);
    this.RC_Frame = $(this.RC_Frame);
    this.RC_Frame.removeClassName(this.hideClass);
    this.setCenterPosition(this.RC_Frame);
    this._is_active = true;
  },

  hide : function() {
    $(this.RC_Frame).addClassName(this.hideClass);
    $(this.RC_Overlay).remove();
    this._is_active = false;
  },

  setCenterPosition : function(element, parent) {
    var w, h, pw, ph;
    var d = Element.getDimensions(element);
    w = d.width;
    h = d.height;
    Position.prepare();
    if (!parent) {
      var viewport = document.viewport.getDimensions();// Position.GetWindowSize();
  pw = viewport.width;
  ph = viewport.height;
} else {
  pw = parent.offsetWidth;
  ph = parent.offsetHeight;
}
element.style.top = '25%';// (ph / 2) - (h / 2) - Position.deltaY + "px";
element.style.left = (pw / 2) - (w / 2) - Position.deltaX + 'px';
},

  create : function(text, heading) {
    var popupId = 'modal_content2';
    if (!heading) {
      heading = 'Warning!';
    }

    if ($(popupId)) {
      $(popupId).remove();
    }

    var frameObj = document.createElement("div");
    frameObj.id = popupId;
    document.body.insertBefore(frameObj, document.body.childNodes[0]);
    frameObj.addClassName('modal_content');
    var html = '<div class="warning_box"> <div class="wrp"> <h3>' + heading
        + '</h3>  <div class="strong">' + text + '</div> </div></div>';
    frameObj.update(html);
    this.RC_Frame = frameObj;
  }

};


// ucfirst
String.prototype.ucfirst = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
}


