jQuery(document).ready(function ($) {
	setSignupInput($);
	setContactInput($);
  clearInputs($);
  setBoxSizes($);
  setMonthlyArchive($);
	setCommentFocus($);
  setCaseStudyHotspot($);
  setStoryLink($);
  handleSingleImageSlideshow($);
  setIEQuotes($);
})

// IE doesn't include quote marks on inline quotes, must do manually here
function setIEQuotes($) {
  if($.browser.msie) {
    $("q").prepend("&quot;").append("&quot;");
  }
}

// Handle single image slide show by hiding slideshow dots
// and extending width of overlay to full width
function handleSingleImageSlideshow($) {
  if ($('.slideshow-overlay').length == 1) {
    $('.slideshow-overlay').show();
    //$('.slideshow-dot').hide();
    $('.slideshow-dot').width(1);
    
    x = $('.views-slideshow-controls-bottom').width();
    $('.slideshow-overlay').width(x);
  }
}

// Home page hover links on blog stories
function setStoryLink($) {
  $(".colm-L li").click(function() {
    var destLink = $(this).find("a:eq(0)").attr("href");
    location.href = destLink;
  });
}

function setCaseStudyHotspot($) {
  $(".case-study-navigation div").click(function() {
		location.href = $(this).find("a").attr("href");
	});
}

// Set yellow border on comment form inputs
function setCommentFocus($) {
  $(".comment-form label").click(function() {
			$(this).next().focus();
	});

  $(".comment-form input, .comment-form textarea").focus(function() {
    $(this).parents(".form-item").addClass("selected");
  }).blur(function() {
    $(this).parents(".form-item").removeClass("selected");
  });
}

// Monthly blog archive - convert to heirarchical representation
function setMonthlyArchive($) {
  $("div.view-archive").children("div.view-content").children("div.item-list").children("ul.views-summary").each(function () {
    
// Parse existing HTML
			// Parse existing HTML
			var years = [];
			var months = [];
			
			$(this).children().each(function () {
				var data = $(this).children().html().split(" ");
				var month = data[0];
				var year = data[1];
				var href = $(this).children().attr("href");
				var ind = -1;
				
				var i=-1;
				while (++i<years.length && years[i] != year);
				if (i < years.length)
					ind = i;
				
				if (ind == -1)
				{
					ind = years.length;
					years.push(year);
					months.push(new Array());
				}
				months[ind].push([month,href]);
			});
						
			// Build new HTML
			var html = '<ul>';
			for (var y=0; y<years.length; y++) {
				html += '<li class="year"><a href="javascript:;" class="' + ((y==0) ? 'downarrow' : 'rightarrow') + '">' + years[y] + '</a>';
				html += '<ul class="sublist"' + ((y==0) ? '' : ' style="display: none;"') + '>';
				for (var m=0; m<months[y].length; m++) {
					var month = months[y][m][0];
					var href = months[y][m][1];
					html += '<li><a href="'+href+'">' + month + '</a></li>';
				}
				html += '</ul></li>';
			}
			
			html += '</ul>';
			
			// Replace the old with the new
			$(this).parent().after(html);
			newArea = $(this).parent().next();
			
			newArea.find("li.year").children("a").click(function () {
				var isOpen = $(this).hasClass("downarrow");
				if (isOpen)
				{
					$(this).addClass("rightarrow").removeClass("downarrow");
					$(this).next().slideUp("fast");
				} else {
					$(this).addClass("downarrow").removeClass("rightarrow");
					$(this).next().slideDown("fast");
					// Close siblings
					$(this).parent().siblings().children("a").removeClass("downarrow").addClass("rightarrow").next().slideUp("fast");
				}
			});
			
			$(this).remove();
  });
}

// Home page bottom panels
function setBoxSizes($) {
  var twitterPanelAdjustment = 9;
  var box1 = $('.region-bottom-first').height();
  var box2 = $('.region-bottom-second').height();
  var box3 = $('.region-bottom-third').height() + twitterPanelAdjustment;
  var max = Math.max(box1, box2, box3);

  if (max > twitterPanelAdjustment) {
    $('.region-bottom-first').height(max);
    $('.region-bottom-second').height(max);
    $('.region-bottom-third').height(max - twitterPanelAdjustment);
  }
}

// Signup form setup
function setSignupInput($){
	var i = 0;
	var signupLabels = Array();
	signupLabels[i++] = 'Email Address';

	$('.region-signup input').each(function () {
		var _el = $(this);
		if (_el.val() == '') {
			_el.val(signupLabels[0]);
		}
		i++;
	});
}

// General form setup
function setContactInput($){
	$('#webform-client-form-756 #edit-submitted-name').each(function () {
		var _el = $(this);
		if (_el.val() != '') {
      _el.parent().addClass('active');
    }
	});
	$('#webform-client-form-756 #edit-submitted-email').each(function () {
		var _el = $(this);
		if (_el.val() != '') {
      _el.parent().addClass('active');
    }
	});
	$('#webform-client-form-756 #edit-submitted-subject').each(function () {
		var _el = $(this);
		if (_el.val() != '') {
      _el.parent().addClass('active');
    }
	});
	$('#webform-client-form-756 #edit-submitted-message').each(function () {
		var _el = $(this);
		if (_el.val() != '') {
      _el.parent().addClass('active');
    }
	});
}

// Clear input fields on focus unless user typed in something
function clearInputs($){
    $('input:text, input:password, textarea').each(function(){
        var _el = $(this);
        var _val = _el.val();
        var _set = !_el.parent().hasClass('active');
        _el.bind('focus', function(){
            if((this.value == _val) && _set) {
              _el.parent().addClass('active');
              this.value = '';
            }
        }).bind('blur', function(){
            if((this.value == '') && _set) {
              _el.parent().removeClass('active');
              this.value = _val;
            }
        });
    });
};
var thumbnailviewer={
enableTitle: false, //Should "title" attribute of link be used as description?
enableAnimation: true, //Enable fading animation?
definefooter: '<div class="footerbar">Close Window X</div>', //Define HTML for footer interface
defineLoading: '<img src="/sites/usercentric.com/themes/d7usercentric/images/loading.gif" /> Loading Image...', //Define HTML for "loading" div

/////////////No need to edit beyond here/////////////////////////

scrollbarwidth: 16,
opacitystring: 'filter:progid:DXImageTransform.Microsoft.alpha(opacity=10); -moz-opacity: 0.1; opacity: 0.1',
targetlinks:[], //Array to hold links with rel="thumbnail"

createthumbBox:function(){
//write out HTML for Image Thumbnail Viewer plus loading div
document.write('<div id="thumbBox" onClick="thumbnailviewer.closeit()"><div id="thumbImage"></div>'+this.definefooter+'</div>')
document.write('<div id="thumbLoading">'+this.defineLoading+'</div>')
this.thumbBox=document.getElementById("thumbBox")
this.thumbImage=document.getElementById("thumbImage") //Reference div that holds the shown image
this.thumbLoading=document.getElementById("thumbLoading") //Reference "loading" div that will be shown while image is fetched
this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
},


centerDiv:function(divobj){ //Centers a div element on the page
var ie=document.all && !window.opera
var dom=document.getElementById
var scroll_top=(ie)? this.standardbody.scrollTop : window.pageYOffset
var scroll_left=(ie)? this.standardbody.scrollLeft : window.pageXOffset
var docwidth=(ie)? this.standardbody.clientWidth : window.innerWidth-this.scrollbarwidth
var docheight=(ie)? this.standardbody.clientHeight: window.innerHeight
var docheightcomplete=(this.standardbody.offsetHeight>this.standardbody.scrollHeight)? this.standardbody.offsetHeight : this.standardbody.scrollHeight //Full scroll height of document
var objwidth=divobj.offsetWidth //width of div element
var objheight=divobj.offsetHeight //height of div element
var topposition=(docheight>objheight)? scroll_top+docheight/2-objheight/2+"px" : scroll_top+10+"px" //Vertical position of div element: Either centered, or if element height larger than viewpoint height, 10px from top of viewpoint
divobj.style.left=docwidth/2-objwidth/2+"px" //Center div element horizontally
divobj.style.top=Math.floor(parseInt(topposition))+"px"
divobj.style.visibility="visible"
},

showthumbBox:function(){ //Show ThumbBox div
this.centerDiv(this.thumbBox)
if (this.enableAnimation){ //If fading animation enabled
this.currentopacity=0.1 //Starting opacity value
this.opacitytimer=setInterval("thumbnailviewer.opacityanimation()", 20)
}
},


loadimage:function(link){ //Load image function that gets attached to each link on the page with rel="thumbnail"
if (this.thumbBox.style.visibility=="visible") //if thumbox is visible on the page already
this.closeit() //Hide it first (not doing so causes triggers some positioning bug in Firefox
var imageHTML='<img src="'+link.getAttribute("href")+'" alt="'+link.getAttribute("title")+'" title="Close zoomed image" style="'+this.opacitystring+'" />' //Construct HTML for shown image
if (this.enableTitle && link.getAttribute("title")) //Use title attr of the link as description?
imageHTML+='<br /><div class="cap" style="width: 500px">'+link.getAttribute("title")+'</div>'
this.centerDiv(this.thumbLoading) //Center and display "loading" div while we set up the image to be shown
this.thumbImage.innerHTML=imageHTML //Populate thumbImage div with shown image's HTML (while still hidden)
this.featureImage=this.thumbImage.getElementsByTagName("img")[0] //Reference shown image itself
this.featureImage.onload=function(){ //When target image has completely loaded
thumbnailviewer.thumbLoading.style.visibility="hidden" //Hide "loading" div
thumbnailviewer.showthumbBox() //Display "thumbbox" div to the world!
}
if (document.all && !window.createPopup) //Target IE5.0 browsers only. Address IE image cache not firing onload bug: panoramio.com/blog/onload-event/
this.featureImage.src=link.getAttribute("href")
this.featureImage.onerror=function(){ //If an error has occurred while loading the image to show
thumbnailviewer.thumbLoading.style.visibility="hidden" //Hide "loading" div, game over
}
},

setimgopacity:function(value){ //Sets the opacity of "thumbimage" div per the passed in value setting (0 to 1 and in between)
var targetobject=this.featureImage
if (targetobject.filters && targetobject.filters[0]){ //IE syntax
if (typeof targetobject.filters[0].opacity=="number") //IE6
targetobject.filters[0].opacity=value*100
else //IE 5.5
targetobject.style.filter="alpha(opacity="+value*100+")"
}
else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax
targetobject.style.MozOpacity=value
else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax
targetobject.style.opacity=value
else //Non of the above, stop opacity animation
this.stopanimation()
},

opacityanimation:function(){ //Gradually increase opacity function
this.setimgopacity(this.currentopacity)
this.currentopacity+=0.1
if (this.currentopacity>1)
this.stopanimation()
},

stopanimation:function(){
if (typeof this.opacitytimer!="undefined")
clearInterval(this.opacitytimer)
},


closeit:function(){ //Close "thumbbox" div function
this.stopanimation()
this.thumbBox.style.visibility="hidden"
this.thumbImage.innerHTML=""
this.thumbBox.style.left="-2000px"
this.thumbBox.style.top="-2000px"
},

cleanup:function(){ //Clean up routine on page unload
this.thumbLoading=null
if (this.featureImage) this.featureImage.onload=null
this.featureImage=null
this.thumbImage=null
for (var i=0; i<this.targetlinks.length; i++)
this.targetlinks[i].onclick=null
this.thumbBox=null
},

dotask:function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
if (target.addEventListener)
target.addEventListener(tasktype, functionref, false)
else if (target.attachEvent)
target.attachEvent(tasktype, functionref)
},

init:function(){ //Initialize thumbnail viewer script by scanning page and attaching appropriate function to links with rel="thumbnail"
if (!this.enableAnimation)
this.opacitystring=""
var pagelinks=document.getElementsByTagName("a")
for (var i=0; i<pagelinks.length; i++){ //BEGIN FOR LOOP
if (pagelinks[i].getAttribute("rel") && pagelinks[i].getAttribute("rel")=="thumbnail"){ //Begin if statement
pagelinks[i].onclick=function(){
thumbnailviewer.stopanimation() //Stop any currently running fade animation on "thumbbox" div before proceeding
thumbnailviewer.loadimage(this) //Load image
return false
}
this.targetlinks[this.targetlinks.length]=pagelinks[i] //store reference to target link
} //end if statement
} //END FOR LOOP
//Reposition "thumbbox" div when page is resized
this.dotask(window, function(){if (thumbnailviewer.thumbBox.style.visibility=="visible") thumbnailviewer.centerDiv(thumbnailviewer.thumbBox)}, "resize")


} //END init() function

}

thumbnailviewer.createthumbBox() //Output HTML for the image thumbnail viewer
thumbnailviewer.dotask(window, function(){thumbnailviewer.init()}, "load") //Initialize script on page load
thumbnailviewer.dotask(window, function(){thumbnailviewer.cleanup()}, "unload")
;
//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}
;

function showHide(subText, tag, showText, hideText)
{
  var textBlock=document.getElementById(subText);
  var imgSign=document.getElementById('g'+subText);
  if(textBlock.style.display=='block')
  {
    jQuery('#' + subText).slideToggle('slow');

    tag.innerHTML = showText;
  }
  else
  {
    jQuery('#' + subText).slideToggle('slow');

    tag.innerHTML = hideText;
    var top=((zxcPos(textBlock)[1]+textBlock.offsetHeight+150));
    var wheight=zxcWWHS()[1]+zxcWWHS()[3];
    if (top>wheight){
      window.scroll(0,zxcWWHS()[3]+top-wheight);
    }
  }
}

function zxcPos(zxcobj){
 zxclft=zxcobj.offsetLeft;
 zxctop=zxcobj.offsetTop;
 while(zxcobj.offsetParent!=null){
  zxcpar=zxcobj.offsetParent;
  zxclft+=zxcpar.offsetLeft;
  zxctop+=zxcpar.offsetTop;
  zxcobj=zxcpar;
 }
 return [zxclft,zxctop];
}

function zxcWWHS(){
 if (window.innerHeight) return [window.innerWidth-10,window.innerHeight-10,window.pageXOffset,window.pageYOffset];
 else if (document.documentElement.clientHeight) return [document.documentElement.clientWidth-10,document.documentElement.clientHeight-10,document.documentElement.scrollLeft,document.documentElement.scrollTop];
 return [document.body.clientWidth,document.body.clientHeight,document.body.scrollLeft,document.body.scrollTop];
}
;
// JavaScript Document
jQuery(document).ready(function($) {
		
		var pageUrl = window.location + "";
		var language = pageUrl.substring(pageUrl.lastIndexOf("/") + 1);
		language = language.substring(0, (language.indexOf(".") == -1 ? language.length : language.indexOf(".")));
		
		var selLanguage = '<span class="arrow">English</span>';
		switch (language) {
			case "chinese":
				selLanguage = '<span lang="zh-Hani" class="arrow">中文</span>';
				break;
			case "czech":
				selLanguage = '<span xml:lang="cs" lang="cs" class="arrow">česky</span>';
				break;
			case "russian":
				selLanguage = '<span xml:lang="ru" lang="ru" class="arrow">русский</span>';
				break;
			case "spanish":	
				selLanguage = '<span class="arrow">Espa&ntilde;ol</span>';
				break;			
		}
					
		$("#pagelang").html(selLanguage);
	
		$(".languagemenu").click(function(){
			if($(this).next().is(":visible")){
		 		$(this).next().hide();  }
			else{
		 		$(this).next().show(); }
		});
		$(".show-items").mouseleave(function() {
			$(this).hide();
		})
});
;

