/*Functions*/

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  
  return this.push.apply(this, rest);
};

//A no jQuery remove class function for ie6FixHover function
function removeClassName(element, classname) {

  if (typeof element !== 'object' || typeof classname !== 'string') return;
  var classes = element.className.split(' ');
  var classes_length = classes.length;
  
  if (classes_length) {
    var i = 0;
    while (i < classes_length && classes[i] != classname) {
      i++;
    }
    
    if (i < classes_length) {
      classes.remove(i);
      element.className = classes.join(' ');
    }
  }
}

/*Events*/

//Events for tabs in Home page
function tabsEvents(selector) {
  /*$(selector).tabs(selector + ' .tab-text', {
    tabs: '.tab-title h3',
    effect: 'horizontal',
    event: 'click'
  });*/
	$('.tab', selector).hover(function(e){
		var minWidth = 180;
		var maxWidth = 440;
		var tab = $(this);
		var open_tab = $('.tab-open', selector).eq(0);
		if ($(tab).hasClass('tab-open')) return;
		$(open_tab).animate({width: minWidth+"px"}, { queue:false, duration:450 }).removeClass('tab-open');
		$(tab).animate({width: maxWidth+"px"}, { queue:false, duration:450}).addClass('tab-open');
	});
}

//Events for the toolbox in Company View
function toolboxEvents() {
  $('#btn-toolbox').click(function(e) {
    $("#financial-toolbox").toggleClass('expanded');
    $('#toolbox-body').toggle();
    ie6FixFooter();
    e.preventDefault();
    var date = new Date();
    date.setTime(date.getTime()+(24*60*60*1000));
    document.cookie = 'toolbox=' + ($("#financial-toolbox").hasClass('expanded') ? '1' : '0') + '; expires=' + date.toGMTString() +'; path=/'
  });
  
  ieFixCheckboxOnchange('input#chk-common, input#chk-forecast');
  
  $('select#sel-current, select#sel-measurement, input#chk-common, input#chk-forecast').change(function() {
    $('#ajax-loader').show();
	var queryLoc = window.location.href.indexOf('?');
    var newLoc = "";
    if (queryLoc > 0) {
      newLoc = window.location.href.substr(0, queryLoc);
    }
    else {
      newLoc = window.location.href;
    }
    if (newLoc.substr(-1) == '#') {
      newLoc = newLoc.substr(0, -1);
    }
    var page = 'page=';
    if ($('input#chk-forecast').attr('checked') == true) {
      page += '-1';
    }
    else {
      var pageIndex = window.location.search.indexOf('page=');
      if (pageIndex) {
        var pageNum = parseInt(window.location.search.substr(pageIndex + 5, 1));
        if (pageNum) {
          page += pageNum;
        }
      }
      else {
        page += '0';
      }
    }
    window.location = newLoc + '?' + page + '&currency=' + $('select#sel-current option:selected').val() + '&m_unit=' + $('select#sel-measurement option:selected').val() + '&common=' + ($('input#chk-common').attr('checked') == true ? '1' : '0');
  });
  
  $('span.lnk-help').tooltip({
    tip: '#help-tooltip',
    relative: true,
    position: 'bottom right',
    offset: [0, -40],
    predelay: 400
  });  
}

//Events for Company View Table
function gridEvents(selector) {
  $(selector).click(function(e) {
    var el = e.target;
    
    //Expand/Collapse single line
    if ((el.className == 'expand' || el.className == 'collapse')) {
      var tr = $(el).parent().parent();
      if (tr.next().hasClass('row-child')) {
        $(tr).toggleClass('row-parent-expanded');
        ($(tr).next().css('display') == 'none')? $(tr).next().show() : $(tr).next().hide();
        ($(el).text() == '+') ? $(el).text('–') : $(el).text('+');
        ($(el).hasClass('expand')) ? el.className = 'collapse' : el.className = 'expand';
      }
      ie6FixFooter();
      e.preventDefault();
    }
    
    //Expand all
    if (el.id == 'expand-all') {
      $('tr.row-parent:not(tr.row-parent-expanded)', selector).each(function() {
        if ($(this).next().hasClass('row-child')) {
          var expand_icon = $('.expand, .collapse', this).get(0);
          $(this).toggleClass('row-parent-expanded');
          //$().toggle() in not working on TR elements in IE8 (1.3.2) so going oldschool on it
		  $(this).next().show();
          $(expand_icon).text('–');
          expand_icon.className = 'collapse';
        }
      });
      ie6FixFooter();
      e.preventDefault();
    }
    
    //Collapse all
    if (el.id == 'collapse-all') {
      $('tr.row-parent-expanded', selector).each(function() {
        var expand_icon = $('.expand, .collapse', this).get(0);
        $(this).toggleClass('row-parent-expanded');
        $(this).next().hide();
        $(expand_icon).text('+');
        expand_icon.className = 'expand';
      });
      ie6FixFooter();
      e.preventDefault();
    }
  });
  
  //Tooltips for Company View
  $('td span.row-number', selector).tooltip({
    tip: '#tooltip',
    relative: true,
    position: 'bottom center',
    offset: [2, 0],
    lazy: false,
    predelay: 400,
    onBeforeShow: function() {
      var _title = $('td.col-item span', this.getTrigger().parent().parent()).text();
      var _year = $('th.col-' + (this.getTrigger().parent().prevAll().length - 1) + ' span').text();
      var _currency = currency;
      var _m_unit = (m_unit == 'Normal') ? '' : ' in ' + m_unit;
      var _value = this.getTrigger().text();
      var _tip = this.getTip();
      var _credibility = $('span.row-credibility', this.getTrigger().parent()).text();
      var _cred_color = _credibility < 75 ? '#af0000' : '#006f05';
      var _haircut = $('span.row-haircut', this.getTrigger().parent()).text();
      var _haircut_color = _haircut < 75 ? '#af0000' : '#006f05';
      var _html_details = ['<h4>', _title, '</h4><span>For the Year ', _year, '</span>'];
      if (_currency) {
        _html_details = _html_details.concat(['<span>', _currency, _m_unit, '</span><span>Credibility: <strong style="color:', _cred_color, '">', _credibility, '%</strong></span><span>Haircut: <strong style="color:', _haircut_color, '">', _haircut, '%</strong></span>']);
      }
      $('.details', _tip).html(_html_details.join(''));
      $('.value', _tip).html(_value);
    },
    onShow: function() {
      $('#tip-container .value').css('line-height', $("#tip-container .details").height() + 'px');
    }
  }).dynamic();
    
  $('th span', selector).tooltip({
    tip: '.year-tooltip',
    relative: true,
    lazy: false,
    position: 'bottom center',
    offset: [2, -10],
    predelay: 400
  });  
}

//Make Company View Header Float
function headerHover(selector) {
  $(window).scroll(function() {
    headerHoverUpdate(selector);
  });
}

//Helper function for headerHover
function headerHoverUpdate(selector) {
  var el = $(selector);
  if ($(window).scrollTop() >= el.parent().offset().top) {
    if (el.css('position') != 'absolute') {
      el.css({
        'position': 'absolute',
        'top': 0
      });
      el.next().css({
        'padding-top': el.height()
      });
    }
	    
    el.css({
      'top': $(window).scrollTop() - el.parent().offset().top
    });
  }
  else if (el.css('position') != 'static') {
    el.css({
      'position': 'static'
    });
    el.next().css({
      'padding-top': 0
    });
  }  
}

//Events for Company Search
function searchEvents(selector) {
  $(selector).click(function(e) {
    var el = e.target;
    if (el.nodeType == 3 || el.nodeName == 'SPAN') {
      el = el.parentNode;
    }
    
    //Add condition button
    if (el.id == 'add-condition') {
      $('#conditions-list').append('<li>' + $('#condition').html() + '</li>');
      ie6Hover('#conditions-list li:last');
      $('#conditions-list li:last .item-select').change(function() {
        searchItemChange(this);
      });
      $('#conditions-list li:last input').focus(function() {
        resetInputValue(this, 'focus');
      }).blur(function() {
        resetInputValue(this, 'blur');
      });
      ie6FixFooter();
      e.preventDefault();
    }
    
    
    //Discard condition button
    if (el.className.indexOf('discard-condition') >= 0) {
      if ($(el).parents('li').siblings().length) {
        $(el).parents('li').remove();
      }
      ie6FixFooter();
      e.preventDefault();
    }
    
    //Submit conditions form.
    if (el.id == 'update-results') {
      $("form#conditions-form").submit();
      e.preventDefault();
    }
    
  });
  
  //Disable unsupported form elements for items
  $('.item-select', selector).change(function() {
    searchItemChange(this);
  });
  
  //Reset input value for empty values
  $('input', selector).focus(function() {
    resetInputValue(this, 'focus');
  }).blur(function() {
    resetInputValue(this, 'blur');
  });
}

//Helper function to reset input value for empty values
function resetInputValue(el, event) {

  switch (event) {
    case 'focus':
      if (el.value == 'Value') {
        el.value = '';
      }
    break;
    case 'blur':
      if (el.value == '') {
        el.value = 'Value';
      }
    break;
  }
}

//Helper function to isable unsupported form elements for items
function searchItemChange(el) {
  var optgroup = el.value.substring(0, el.value.indexOf('|'));
  if (optgroup != 'Accounts') {
    $(el).parent().nextAll('.term').children('input,select').each(function() {
      $(this).attr('disabled', 'disabled');
    });
  }
  else {
    $(el).parent().nextAll('.term').children('input,select').each(function() {
      $(this).removeAttr('disabled');
    });
  }
}

//Fix IE Checkbox onchange behaveior
function ieFixCheckboxOnchange(el) {
    if ($.browser.msie) {
        $(el).click(function () {
            this.blur();
            this.focus();
        });
    }
}


//Emulate hover on IE6 for selected elements
function ie6Hover(elements) {
  if (window.XMLHttpRequest) return;
  
  $(elements).each(function() {
    $(this).hover(function() {
      this.className += ' hover';
    }, function() {
      removeClassName(this, 'hover');
    });
  });
}

//Fix footer location in ie6, used when changing document height
function ie6FixFooter() {
  if (window.XMLHttpRequest) return;
  if ($(window).height() + 5 <= $(document).height()) {
    if ($('#footer').css('position') != 'static') {
      $('#footer').css({
        'position': 'static'
      });
      $('#main').css({
        'padding-bottom': '0'
      });
    }
  }
  else {
    $('#footer').css({
      'position': 'absolute'
    });
    $('#main').css({
      'padding-bottom': '51px'
    });
  } 
}

function hidePlayerTooltip(){
	$('#player-tooltip').fadeOut('slow');
	$('body').unbind('click', hidePlayerTooltip);
  clearTimeout(playerToolTipTimeout);
}

var playerToolTipTimeout = null;

//Run on Document Ready
$(document).ready(function() {

  //Home page
  if ($('#tabs').length) {
    tabsEvents('#tabs');
  }
  //Company View
  if ($('#grid-data').length) {
    toolboxEvents();
	$('#ajax-loader').hide();
    gridEvents('#grid-data, #grid-headers');
    headerHover('#grid-headers');
    ie6Hover('#grid-data tr:not(tr.row-child), #grid-data td.col-number');
  }
  //Search
  if ($('#query-container').length) {
    searchEvents('#query-container');
	ie6Hover('#conditions-list li, #results-list tr');
  }
  if ($('#player').length) {
	  
    // install flowplayer into flowplayer container 
    var player = $f("player", "/static/flowplayer-3.1.5.swf", {
		clip: {
		  url: clip_url,
		  scaling: 'fit'		  
		},
		plugins:{
			controls:{
				autoHide:'always'
			}	
		}
	}); 
    // setup button action. it will fire our overlay  
    $("span[rel]").overlay({
    	closeOnClick 	: true,
        top 			: 'center',
    	onLoad			: function() { 
                            player.load();
                        }, 
        onClose			: function() { 
                            player.unload(); 
                        },
        expose			: { 
                            color: '#fff', 
                            loadSpeed: 200, 
                            opacity: 0.7 
                        }
    }); 
    if ($.cookie('playerToolTip_' + clip_page) != '1') {
      $('#player-tooltip').fadeIn('slow').fadeTo('0', 0.8);
      $.cookie('playerToolTip_' + clip_page, '1');
      $("body").bind("click", hidePlayerTooltip);
      playerToolTipTimeout = setTimeout("hidePlayerTooltip()", 12000);
    }
  }

});

