$(document).ready(function(){

    /*contact preselector*/
    if (window.location.pathname === '/contact/'){
        var selectedOption = window.location.hash;
        if (selectedOption === '') $('#subject option').removeAttr('selected');
        switch(selectedOption) {
           case '#business':
               $('#subject option[value="business"]').attr({'selected':'selected'});
               break;
           case '#pr':
               $('#subject option[value="pr"]').attr({'selected':'selected'});
               break;
           case '#support':
               $('#subject option[value="support"]').attr({'selected':'selected'});
               break;
           case '#careers':
               $('#subject option[value="careers"]').attr({'selected':'selected'});
               $('#file_attachment_row').slideDown();
               break;
           case '#general':
               $('#subject option[value="general"]').attr({'selected':'selected'});
               break;
          case '#webinar':
               $('#subject option[value="webinar"]').attr({'selected':'selected'});
               break;
        case '#cgevents':
               $('#subject option[value="cgevents"]').attr({'selected':'selected'});
               break;
        }
    }


    /* SEARCH input replacement */
    var searchInput = $('input#query');
    var searchLabel = "Search";
    searchInput.css("color","#50301c")
               .focus(
                    function(){
                        if (searchInput.attr('value') === searchLabel) {
                            searchInput.attr("value","")
                                       .css("color","#000");
                        }
                    }
               )
               .blur(
                    function(){
                        if (searchInput.attr("value")==="") {
                            searchInput.attr("value",searchLabel)
                                       .css("color","#50301c");
                        }
                    }
               );

});

function filterCases(type, target_id) {
  
  var url="/ajax/filter_cases.php";
  url=url+"?type="+type;
  url=url+"&target_id="+target_id;
  url=url+"&sid="+Math.random();
  
  if (type != 'all') {
  
    $.ajax({
      url : url,
      contentType : 'html',
      success : function(data) {
        $('#landing_content').slideUp();
        $('.icon_overlay').each(function() {
          $(this).removeClass('grayed');
          $(this).removeAttr('disabled');
        });
        var ids = data.split(',');
        $('.icon_overlay').each(function() {
          var current_element = $(this).attr('id');
          var current_element_id = current_element.replace('overlay_', '');
          if (jQuery.inArray(current_element_id, ids)==-1) {
            $(this).addClass('grayed');
            $(this).attr('disabled', 'disabled');
          }
        });
        $('.sort_type').css({'background-color': '#fff'});
        $('#' + type + '_sort_type').css({'background-color': '#eee'});
      }
    });
  } else {
    if($('#landing_content').css('display') !== 'none') $('#landing_content').slideUp();
    $('.icon_overlay').removeClass('grayed');
    $('.icon_overlay').removeAttr('disabled');
    $('.sort_type').css({'background-color': '#fff'});
  }
   
}

function displayNewsItems(current_page, type, start) {
  
  if (start === undefined) {
    start = 0;
  }
  
  if (type == 'hash') {
  
    if (location.href.indexOf('#')>-1) {
      var position = location.href.search('#');
      var anchor = location.href.substr(position+1);
      if (anchor.length>0) {
        type = anchor
      } else {
        type = 'all'
      }
    } else {
      type = 'all'
    }
  
  }
  
  var url="/ajax/display_news_items.php";
  url=url+"?current_page="+current_page;
  url=url+"&type="+type;
  url=url+"&sid="+Math.random();
  
  $.ajax({
    url : url,
    contentType : 'html',
    success : function(data) {
      
      var result = data.split('|');
      
      var news_container = $('#news_item_container');
      if (start!=1) {
        news_container.fadeOut('slow', function() {
          news_container.html(result[0])
        });
      } else {
        news_container.html(result[0])
      }
      
      news_container.fadeIn('slow');
      if ((result[1]!='all')&&(result[1]!='')&&(result[1]!='detail')) {
        window.location.hash = result[1]
      } else {
        window.location.hash = ''
      }
      // smoothScroll('masthead');
    }
  });
  if ($('#secondary_nav a').hasClass('active')){
        $('#secondary_nav a').removeClass('active');
        $('#secondary_nav a#'+type).addClass('active');
    }
}

function chooseContactFormType(type) {
  
  if (type=='careers') {
    $('#file_attachment_row').slideDown();
  } else {
    $('#file_attachment_row').slideUp();
  }
  
  return true
  
}

/*************************/
/* SUPPORTING FUNCTIONS */
/*************************/

function currentYPosition() {
	if (self.pageYOffset) return self.pageYOffset;
	
	if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop;
	
	if (document.body.scrollTop) return document.body.scrollTop;
	
	return 0;
}
function elmYPosition(eID) {
	var elm  = document.getElementById(eID);
	var y    = elm.offsetTop;
	var node = elm;
	while (node.offsetParent && node.offsetParent != document.body) {
		node = node.offsetParent;
		y   += node.offsetTop;
	} return y;
}
function smoothScroll(eID) {
	var startY   = currentYPosition();
	var stopY    = elmYPosition(eID);
	var distance = stopY > startY ? stopY - startY : startY - stopY;
	if (distance < 100) {
		scrollTo(0, stopY); return;
	}
	var speed = Math.round(distance / 100);
	var step  = Math.round(distance / 25);
	var leapY = stopY > startY ? startY + step : startY - step;
	var timer = 0;
	if (stopY > startY) {
		for ( var i=startY; i<stopY; i+=step ) {
			setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
			leapY += step;
			if (leapY > stopY) leapY = stopY;
			timer++;
		} return;
	}
	for ( var i=startY; i>stopY; i-=step ) {
		setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
		leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
	}
}

// STYLING FILE INPUTS 1.0 | Shaun Inman <http://www.shauninman.com/> | 2007-09-07
if ($('#contact')){
    if (!window.SI) { var SI = {}; }
    SI.Files =
    {
     htmlClass : 'styled_file',
     fileClass : 'attachment',
     wrapClass : 'attachment_wrapper',

     fini : false,
     able : false,
     init : function()
     {
     this.fini = true;

     var ie = 0 //@cc_on + @_jscript_version
     if (window.opera || (ie && ie < 5.5) || !document.getElementsByTagName) { return; } // no support for opacity or the DOM
     this.able = true;

     var html = document.getElementsByTagName('html')[0];
     html.className += (html.className != '' ? ' ' : '') + this.htmlClass;
     },

     stylize : function(elem)
     {
     if (!this.fini) { this.init(); };
     if (!this.able) { return; }

     elem.parentNode.file = elem;
     elem.parentNode.onmousemove = function(e)
     {
     if (typeof e == 'undefined') e = window.event;
     if (typeof e.pageY == 'undefined' && typeof e.clientX == 'number' && document.documentElement)
     {
     e.pageX = e.clientX + document.documentElement.scrollLeft;
    e.pageY = e.clientY + document.documentElement.scrollTop;
     };

     var ox = oy = 0;
     var elem = this;
     if (elem.offsetParent)
     {
     ox = elem.offsetLeft;
     oy = elem.offsetTop;
     while (elem = elem.offsetParent)
     {
     ox += elem.offsetLeft;
     oy += elem.offsetTop;
     };
     };

     var x = e.pageX - ox;
     var y = e.pageY - oy;
     var w = this.file.offsetWidth;
     var h = this.file.offsetHeight;

     this.file.style.top = y - (h / 2) + 'px';
     this.file.style.left = x - (w - 30) + 'px';
     };
     },

     stylizeById : function(id)
     {
     this.stylize(document.getElementById(id));
     },

     stylizeAll : function()
     {
     if (!this.fini) { this.init(); };
     if (!this.able) { return; };

     var inputs = document.getElementsByTagName('input');
     for (var i = 0; i < inputs.length; i++)
     {
     var input = inputs[i];
     if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass) != -1)
     {
     this.stylize(input);
     }
     }
     }
    };
}
function tabNav () {
    var tabs = $('#tabs h3, #tabs h4');
    tabs.click(function(){
        var tid = $(this).attr('id'),
            clickedTab = $('#' + tid),
            clickedContent = $('#' + tid + '_content');
        if (!clickedTab.hasClass('active')){
            tabs.removeClass('active');
            clickedTab.addClass('active');
            $('.tabbed_content').hide();
            clickedContent.show();
        }
    });
}
