/* global.js */
$(document).ready(function() {
	$('.feedback_link').fancyZoom({directory: "/images/fancyzoom", closeOnClick: false});
});

(function($) {

  $.fn.extend({
    computedStyle : function(prop)
    {
      if (typeof(this.get(0).currentStyle) != 'undefined') { // ie
        var match;
        while (match = prop.match(/(.*)-(\w)(.*)/)) {
        var e;
            prop = match[1] + match[2].toUpperCase() + match[3];
        }
        return this.get(0).currentStyle[prop];
      } else {
        return document.defaultView.getComputedStyle(this.get(0), null)
                                   .getPropertyValue(prop);
      }
    }
  });

  function _customSelectElementHtml(id, i, value, text, hidden)
  {
    var html = '<div class="option" '
             +      'id="' + id + '_customSelect_' + i + '" '
             +      'value="' + value + '" '

    if (hidden) {
      html += 'style="display:none;" ';
    }

    html += '>'
         + text
         + '</div>';

    return html;
  }

  function _customSelectScroll(direction)
  {
    var isUp = direction == 'up';
    var options = this.find('> div.option');

    if (options.filter(':' + (isUp ? 'first' : 'last')).is(':visible')) {
      return;
    }
    options.filter(':visible:' + (isUp ? 'last' : 'first')).hide();
    options.filter(':visible:' + (isUp ? 'first' : 'last'))[isUp ? 'prev' : 'next']().show();

    if (options.filter(':' + (isUp ? 'first' : 'last')).is(':visible')) {
      this.find('> div.scroll-' + direction).addClass('disabled');
    }

    this.find('> div.scroll-' + (isUp ? 'down' : 'up')).removeClass('disabled');
  }

  $.fn.extend({
    absoluteOffset : function()
    {
      if ($.browser.msie) {
        return this.offset();
      }
      var offset = this.offset();
      var offsetParent = $(this.get(0).offsetParent)
      if (!offsetParent.is('body')) {
        var parentOffset = offsetParent.offset();
        offset = {
          'left' : offset['left'] + parentOffset['left'],
          'top'  : offset['top']  + parentOffset['top']
        };
      }
      return offset;
    },

    customSelect : function(options)
    {
      /*
       * parse options
       */
      var id = this.attr('id')
      if (typeof(options.value)     == 'undefined') { options.value   = ''; }
      //if (typeof(options.maxOptions) == 'undefined') { options.maxOptions = null; }
      options.maxOptions = 100000; // Lee Hack To Show Scroll Bar
      if (typeof(options.scrollTimeout) == 'undefined') { options.scrollTimeout = 200; }
      className = 'custom-select'
                + ( (typeof(options.className) != 'undefined')
                  ? (' ' + options.className)
                  : '');

      /*
       * build drop down html and add to DOM
       */
      var dropDown = '<div class="' + className + '" '
                   +      'id="' + id + '_customSelect" ';
      if (options.maxOptions) {
        dropDown  +=      '_maxOptions="' + options.maxOptions + '" ';
      }
      dropDown    +=      'style="display:none; overflow: scroll;">';

      //if (options.maxOptions) { // scrolling
      //  dropDown += '<div class="scroll-up disabled"></div>'
      //}

      $(options.options).each(function(i) {
        dropDown += _customSelectElementHtml(
          id,
          i,
          this.value,
          this.text,
          (options.maxOptions !== null) && i >= options.maxOptions
        );
      });

      //if (options.maxOptions) { // scrolling
      //  dropDown += '<div class="scroll-down';
      //  if (options.options.length <= options.maxOptions) {
      //    // not enough options to scroll
      //    dropDown += ' disabled';
      //  }
      //  dropDown += '"></div>';
      //}

      dropDown += '</div>';

      $(document.body).append(dropDown);

      var scrolling = false;

      /*
       * select click
       */
      function openMe() {
        var offsets = $(this).absoluteOffset();

        $('#' + id + '_customSelect').css({
          'position'   : 'absolute',
          'overflow-x' : 'hidden',
          'overflow-y' : 'visible',
          'top'        : (offsets['top'] + $(this).height()) + 'px',
          'left'       : (offsets['left'] +
                        parseInt($(this).computedStyle('padding-left'))) + 'px',
          'min-width'  : $(this).width() + 'px'
          /* ,
          'color'      : $(this).computedStyle('color'),
          'font-size'  : $(this).computedStyle('font-size'),
          'font-weight': $(this).computedStyle('font-weight')
          */
        }).show();

        // bind when the event is propagated to body,
        // might have to change this for ie
        $(document.body).one('click', function() {
          $(document.body).one('click', function() {
            if (!scrolling) {
              $('#' + id + '_customSelect').hide();
              $('#' + id).one('click', openMe);
            }
          })
        });
      };

      this.one('click', openMe);

      /*
       * row clicks
       */
      $('#' + id + '_customSelect > div.option').bind('click', function() {
        var baseEl = $('#' + id);

        // save these in case callback returns false.
        var save = {'value' : $(baseEl).attr('value'),
                    'html'  : $(baseEl).attr('innerHTML')};

        baseEl.attr({
          'value'     : $(this).attr('value'),
          'innerHTML' : $(this).attr('innerHTML')
        });

        switch (typeof(options.onchange)) {
          case 'function':
            var func = options.onchange;
            break;
          case 'string':
            eval('var func = function(){' + options.onchange + '};');
            break;
          default:
            var func = null;
        }

        if (func) {
          result = func.apply(baseEl.get(0), arguments);
          if ((typeof(result) != 'undefined') && !result) {
            baseEl.attr({
              'value'     : save['value'],
              'innerHTML' : save['html']
            });
          }
        }
      });

/*
      function switchColors(el)
      {
        var bgColor = $(this).computedStyle('background-color');
        if (!bgColor || bgColor == 'transparent') { bgColor = '#FFFFFF'; }
        $(this).css({'color'            : bgColor,
                     'background-color' : $(this).computedStyle('color')});
      }
*/

      /*
       * row mouseovers
       */
      $('#' + id + '_customSelect > div').bind('mouseover', function() {
        // switchColors.call(this);
        $(this).addClass('over').one('mouseout', function() {
          // switchColors.call(this);
          $(this).removeClass('over');
        });
      });

      /*
       * scroller events
       */
      if (options.maxOptions) {
        var timeouts = {};
        $(['up', 'down']).each(function() {
          // vars closed in function will hold their values
          var dir     = this;
          var scrollFunc = function() {
            scrolling = true;
            _customSelectScroll.call($('#' + id + '_customSelect'), dir);
            timeouts[dir] = setTimeout(scrollFunc, options.scrollTimeout);
          }
          $('#' + id + '_customSelect > div.scroll-' + dir)
              .bind('mouseover', scrollFunc)
              .bind('mouseout',  function() {
                scrolling = false;
                clearTimeout(timeouts[dir]);
              })
              .bind('click', function() {
                for (var i = 0; i < options.maxOptions - 1; i++) {
                  _customSelectScroll.call($('#' + id + '_customSelect'), dir);
                }
              });
        });
      }
    },

    removeCustomSelectOption : function(value)
    {
      var id = this.attr('id');
      var options = $('#' + id + '_customSelect > div.option');
      options.each(function() {

        if (value == $(this).attr('value')) {
          if (options.filter(':first').is(':visible')) {
            options.filter(':hidden:first').show();
            if (options.filter(':last').is(':visible')) {
              $('#' + id + '_customSelect > div.scroll-down')
                                                          .addClass('disabled');
            }
          } else {
            options.filter(':visible:first').prev().show();
            if (options.filter(':first').is(':visible')) {
              $('#' + id + '_customSelect > div.scroll-up')
                                                          .addClass('disabled');
            }
          }

          $(this).remove();
          return false;
        }
      });
    },

    addCustomSelectOption : function(value, text)
    {
      var id = this.attr('id');

      var maxOptions = $('#' + id + '_customSelect').attr('_maxOptions');
      var scroll = maxOptions 
            && ($('#' + id + '_customSelect > div.option').length > maxOptions);
      $('#' + id + '_customSelect > div.option:last').after(
        _customSelectElementHtml(
          id,
          $('#' + id + '_customSelect > div.options').length,
          value,
          text,
          scroll
        )
      );

      if (scroll) {
        $('#' + id + '_customSelect > div.scroll-down').removeClass('disabled');
      }
    }
  });

  // array of hint texts
  var inputHints       = {};
  var inputMaxLength   = {};

  var parentValFunc = $.fn.val;

  $.fn.extend({
    /**
     * setHint() - initialise the input hint.
     *
     * @param string hintText - text to be used when field is empty.
     */
    setHint: function(hintText, options) {

      var domId = this.attr('id');
      var exists = typeof(inputHints[domId]) != 'undefined';
      // Store the Hint Text
      inputHints[domId] = ' ' + hintText;
      // Store maxlength so we can restore it when we clear it
      if (this.attr('maxLength') > 0){
         inputMaxLength[domId] = this.attr('maxLength'); 
      }
      else {
         inputMaxLength[domId] = "";
      }

      if (exists) {
        parentValFunc.call(this, '');
      } else {
        var me = this;
        this.bind('blur',  function() { me.handleHintBlur(); });
        this.bind('focus', function() { me.handleHintFocus(); });
      }

      this.handleHintBlur();
    },

    /**
     * showHint() - shows hint text
     */
    showHint: function()
    {
      this.addClass('inputHint');        
      this.removeAttr("maxLength");      
      return parentValFunc.call(this, inputHints[this.attr('id')]);
    },

    /**
     * hideHint() - hides hint text
     */
    hideHint: function()
    {
      this.removeClass('inputHint');
      if (inputMaxLength[this.attr('id')] != ""){
        this.attr("maxLength", inputMaxLength[this.attr('id')]);
      }
      parentValFunc.call(this, '');
    },

    /**
     * handleHintBlur() - callback for blur of input field
     */
    handleHintBlur: function()
    {
      if (parentValFunc.call(this) === '') {
        this.showHint();
      }
    },

    /**
     * handleHintFocus() - callback for focus of input field
     */
    handleHintFocus: function()
    {
      if (parentValFunc.call(this) == inputHints[this.attr('id')]) {
        this.hideHint();
      }
    },

    /**
     * val() - overrides jquery val() prototype.  If we're getting the value
     *     we make sure not to return the hint text.  If we're setting
     *     the value, we make sure to show the hint text if necessary.
     */
    val: function(value) {

      var domId = this.attr('id');

      if (typeof(inputHints[domId]) == 'undefined') {
        return parentValFunc.call(this, value);
      }

      if (typeof(value) != 'undefined') {      // setting
        if (value == '') {
          return this.showHint(domId);
        } else { 
          this.removeClass('inputHint');
          return parentValFunc.call(this, value);
        }
      } else {                   // getting
        // get the value
        var retVal = parentValFunc.call(this, value);

        return (inputHints[domId] == retVal) ? '' : retVal;
      }
    }
  });
})(jQuery);

// Create new LiveRise Namespace
var LiveRise = new Object();

/***
  ** getPageSize()
  ** Returns array with page width, height and window width, height
  ** Core code from - quirksmode.org
  ** Edit for Firefox by pHaez
  **/
LiveRise.getPageSize = function(){
    
    var xScroll, yScroll;
    
    if (window.innerHeight && window.scrollMaxY) {
	xScroll = document.body.scrollWidth;
	yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
	xScroll = document.body.scrollWidth;
	yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	xScroll = document.body.offsetWidth;
	yScroll = document.body.offsetHeight;
    }
    
    var windowWidth, windowHeight;
    if (self.innerHeight) {// all except Explorer
	windowWidth = self.innerWidth;
	windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	windowWidth = document.documentElement.clientWidth;
	windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
	windowWidth = document.body.clientWidth;
	windowHeight = document.body.clientHeight;
    }
    
    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
	pageHeight = windowHeight;
    } else { 
	pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){
	pageWidth = windowWidth;
    } else {
	pageWidth = xScroll;
    }

    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
    return arrayPageSize;
}

LiveRise.showPopupOverlay = function(){
    var arrayPageSize = LiveRise.getPageSize();
    $("#zoom_overlay").height(arrayPageSize[1]);
    $("#zoom_overlay").fadeIn();
}
LiveRise.hidePopupOverlay = function(){
    $("#zoom_overlay").fadeOut();
}


/***
 ** Home Specific JS
 ***/
// Create new LiveRise.Home Namespace
if (LiveRise.Home == null || typeof(LiveRise.Home) != "object") { LiveRise.Home = new Object(); }

LiveRise.Home = {

    moreInfo : function(item){
        $(item).siblings('.alert_details').slideDown();  
        $(item).hide();
        $(item).siblings('.less').show();
    },
    lessInfo : function(item){
        $(item).siblings('.alert_details').slideUp();
        $(item).hide();
	$(item).siblings('.more').show();
    }

}