
// Vspark
jQuery.extend({
  isUndefined: function(obj){
    return typeof(obj) == "undefined" ? true : false;
  },
  exists: function(obj){
    return jQuery(obj).length != 0 ? true : false ;
  },
  browserDetection: function(appendTo, evalBrowser) {
    var userAgent = navigator.userAgent.toLowerCase();
    if(!evalBrowser){
      var bindToElm = (jQuery.isUndefined(appendTo) ? jQuery("body") : jQuery(appendTo));
      jQuery.browser.chrome = /chrome/.test(userAgent); 
      if(jQuery.browser.msie) { // Is this a version of IE?
        bindToElm.addClass("browser_ie");        
        bindToElm.addClass("browser_ie" + jQuery.browser.version.substring(0,1));
      }
      if(jQuery.browser.chrome) { // Is this a version of Chrome?
        bindToElm.addClass("browser_chrome");
        userAgent = userAgent.substring(userAgent.indexOf("chrome/") +7);
        userAgent = userAgent.substring(0,1);
        bindToElm.addClass("browser_chrome" + userAgent);  
        jQuery.browser.safari = false; // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
      }
      if(jQuery.browser.safari) { // Is this a version of Safari?
        bindToElm.addClass("browser_safari");        
        userAgent = userAgent.substring(userAgent.indexOf("version/") +8);
        userAgent = userAgent.substring(0,1);
        bindToElm.addClass("browser_safari" + userAgent);
      }
      if(jQuery.browser.mozilla) { // Is this a version of Mozilla?
        if(navigator.userAgent.toLowerCase().indexOf("firefox") != -1) { //Is it Firefox?
          bindToElm.addClass('browser_firefox');
          userAgent = userAgent.substring(userAgent.indexOf("firefox/") +8);
          userAgent = userAgent.substring(0,1);
          bindToElm.addClass("browser_firefox" + userAgent);
        } else { // If not then it must be another Mozilla
          bindToElm.addClass("browser_mozilla");
        }
      }
    }
    else{
      var toEval = new RegExp(evalBrowser);
      return toEval.test(userAgent);
    }
  },
  getRootDomain: function(){
    var rootDomain = document.location.hostname;
    if(rootDomain.match(/localhost/gi)){
      return finalDomain = "localhost";
    }
    else{
      var split = rootDomain.split('.');
      return "." + split[split.length-2] + "." + split[split.length-1];
    }  
  },
  getHashValue: function(){
    return window.location.hash;
  },  
   vcookie: function(c_name,value,exdays){
    if(!value){
      var i,x,y,ARRcookies=document.cookie.split(";");
       for (i=0;i<ARRcookies.length;i++)
       {
         x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
         y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
         x=x.replace(/^\s+|\s+$/g,"");
         if (x==c_name)
           {
           return unescape(y);
           }
         }
    }
    else if(value == "remove"){
       var c_value=escape(value) + "; expires=Thu, 1 Aug 1983 20:47:11 UTC";
       document.cookie=c_name + "=" + c_value;
    }
    else{
     var exdate=new Date(exdays);
     var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
     document.cookie=c_name + "=" + c_value;
    }
  },
  elmOverride: function(overrideName,overrideValue,overrideExdays){
    //Do a relay to set cookie and attach override on target parent
    var c_name = overrideName;
    var value = (overrideValue == null ? null : overrideValue);
    var exdays = (typeof(overrideExdays) == 'undefined' ? '' : overrideExdays)

    jQuery.vcookie(c_name.replace(/[#.]/gi,''), value, exdays);
    setFormDefaults().setValues(c_name);
  }  
});
jQuery.fn.extend({
    trunc: function(count, append) {
        //Used for string truncation
          return (isNaN(count)) ? this : this.each(function() {
                var _this = jQuery(this);
                var curCount = 0;
                var boolCount = true;
                var curChar = "";
                var curString = _this.html();
                var tempString = "";
                var truncAppend = append;
                for(var i=0; i<curString.length; i++) {
        curChar = curString.charAt([i]);
        tempString += curChar;
        switch(curChar) {
            case "<":
              boolCount = false;
              break;
            case ">":
              boolCount = true;
              break;
            default:
              if(boolCount) {
                  curCount++;
              }
        }
        if(curCount == count) {
            _this.html(tempString + (jQuery.isUndefined(truncAppend) ? "..." : truncAppend));
            break;
        }
                }
          });
    },
    outerHTML: function(obj){
      return jQuery("<div>").append(jQuery(this).clone()).html();
    },
    popupWindow: function(name, width, height, spec){
      jQuery(this).live('click', function(e){
        e.preventDefault();
        var winName = name.replace(/[ -\/&#]/gi,'');
        var theWidth = (width) ? width : 700;
        var theHeight = (height) ? height : 500;
        var winSpecs = 'width=' + width + ',height=' + height + ',' + (jQuery.isUndefined(spec) ? 'location=0,menuBar=1,resizable=1,scrollbars=1,status=1,toolbar=0,directories=0' : spec);
        window.open(this.href, winName, winSpecs);
    });    
  },
  defaultText: function(activeClass, defautlAttr) {
      //Toggle class based on default value
      var _this = jQuery(this);
      _this.val() != _this.attr(defautlAttr) ? _this.removeClass(activeClass) : (_this.hasClass(activeClass) ? "" : _this.addClass(activeClass));
      _this.focus(function(){
        if(_this.val() == _this.attr(defautlAttr)){
          _this.val('');
          _this.removeClass(activeClass);
        }
      }).blur(function(){
        if(_this.val() == ""){
          _this.val(_this.attr(defautlAttr));
          _this.addClass(activeClass);        
        }
      });

  },
  customTransform: function(configValues){
    var targetObject = jQuery(this);
    jQuery(targetObject).css('display','none');
    var myConfig = {"bindings":[ configValues ]};
    var _objectType = jQuery(targetObject).get(0).tagName.toLowerCase();
    var _objectAddClassContainer = typeof(myConfig.bindings[0].containerClass) == 'undefined' ? '' : myConfig.bindings[0].containerClass;
    var _objectAddClassLabel = typeof(myConfig.bindings[0].labelClass) == 'undefined' ? '' : myConfig.bindings[0].labelClass;
    var _objectAddClassDrop = typeof(myConfig.bindings[0].dropClass) == 'undefined' ? '' : myConfig.bindings[0].dropClass;
    var _objectDoPostBack = typeof(myConfig.bindings[0].postBack) == 'undefined' ? '' : myConfig.bindings[0].postBack;
    var _objectDoCallback = typeof(myConfig.bindings[0].callBack) == 'undefined' ? '' : myConfig.bindings[0].callBack;

      //More templates can be added to this, just add else + element type to extend.
      if(_objectType == 'select'){
        var selected = jQuery(':selected', targetObject).text();
        jQuery(targetObject).after(
         '<div class=\"uxselect select ' + _objectAddClassContainer + '\">'
          +'<a class=\"label ' + _objectAddClassLabel + '\" href=\"javascript:void(0);\"><span>' + selected + '</span></a>'
          +'<div style=\"display:none;\" class=\"dropdown ' + _objectAddClassDrop + '\"><ul></ul></div></div>'
         );
         
        var currentObj = jQuery('.uxselect.' + _objectAddClassContainer);
        jQuery('option', targetObject).each(function(){
            jQuery(this).attr('data-default') ? "" : jQuery('.dropdown ul', currentObj).append('<li><a data-value=\"' + jQuery(this).val() + '\" href=\"javascript:void(0);\">' + jQuery(this).text() + '</a></li>');
        });  
        
        jQuery('.dropdown a', currentObj).live('click', function(e){
          e.preventDefault();
          var text = jQuery(this).text();
          var index = jQuery(this).parent('li').index();
          jQuery('.label span', currentObj).html(jQuery(this).text());
          jQuery('option:eq(' + index + ')', jQuery(targetObject)).attr('selected', 'selected');
          jQuery('div.dropdown', currentObj).css('display','none');
          
          //If a postback is needed, get the postback value from the original select box and append to custom box.
          if(_objectDoPostBack != ''){
            javascript:setTimeout('__doPostBack(\'' + jQuery(targetObject).attr('name') + '\',\'\')', 50);
           }

          //Makes a callback once a new value is selected. Passes original option value & text  
          if(_objectDoCallback != ''){
            _objectDoCallback(jQuery(this).attr('data-value'), jQuery(this).text());
          }
        });
        
        jQuery('a.label', currentObj).live('click', function(){
          jQuery(this).next('div.dropdown').css('display','block');
          jQuery(this).parents('.uxselect').one('mouseleave', function(){
            jQuery('.dropdown', this).css('display','none');
          });
          });
     }
  }
});



var userAgent = navigator.userAgent.toLowerCase();
jQuery(browserDetection);

/* ----------------------------------------------------------------------------	
Begin functions
*/

// -------------------------------------------------------------------------
// Begin "Browser detection"
function browserDetection() {
	jQuery.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase()); 
	if(jQuery.browser.msie) { // Is this a version of IE?
		jQuery("body").addClass("IE");        
		jQuery("body").addClass("IE" + jQuery.browser.version.substring(0,1));
	}
	if(jQuery.browser.chrome) { // Is this a version of Chrome?
		jQuery("body").addClass("Chrome");
		userAgent = userAgent.substring(userAgent.indexOf("chrome/") +7);
		userAgent = userAgent.substring(0,1);
		jQuery("body").addClass("Chrome" + userAgent);  
		jQuery.browser.safari = false; // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
	}
	if(jQuery.browser.safari) { // Is this a version of Safari?
		jQuery("body").addClass("Safari");        
		userAgent = userAgent.substring(userAgent.indexOf("version/") +8);
		userAgent = userAgent.substring(0,1);
		jQuery("body").addClass("Safari" + userAgent);
	}
	if(jQuery.browser.mozilla) { // Is this a version of Mozilla?
		if(navigator.userAgent.toLowerCase().indexOf("firefox") != -1) { //Is it Firefox?
			jQuery("body").addClass('Firefox');
			userAgent = userAgent.substring(userAgent.indexOf("firefox/") +8);
			userAgent = userAgent.substring(0,1);
			jQuery("body").addClass("Firefox" + userAgent);
		} else { // If not then it must be another Mozilla
			jQuery("body").addClass("Mozilla");
		}
	}
}
// End "Browser detection"

// -------------------------------------------------------------------------
// Begin "Initializing Blades - Expand / Collapse"
function iniBlades(objTarget, objSlider, objStatus, textTarget, closedText, openText, position) {
	jQuery(objTarget).click(function(e){
		e.preventDefault();
		if(position=="after") {
			jQuery(this).parents(objStatus).find(objSlider).slideToggle('fast');
		} else if(position=="before") {
			jQuery(this).parents(objStatus).find(objSlider).slideToggle('fast');
		} else {
			jQuery(this).parents(objStatus).find(objSlider).slideToggle('fast');
		}
		jQuery(this).parents(objStatus).toggleClass("active");
		if(closedText && openText) {
			if(jQuery(this).parents(objStatus).hasClass("active")) {
				jQuery(textTarget).text(openText);
			} else {
				jQuery(textTarget).text(closedText);	
			}	
		}
	});
}
// End "Initializing Blades - Expand / Collapse"


function iniTour() {
	jQuery('#TakeTheTour').cycle({
		timeout:8000,
		fx: 'fade',
		speed: 500,
		nowrap:1,
		after: function(currSlideElement, nextSlideElement, options, forwardFlag)   {
			var _this =  parseInt($j(nextSlideElement).attr('rel'));
			if(_this == (jQuery('#TakeTheTour').children().length-1)) {
				var openModal = setTimeout( function() {
					jQuery(".modal_content").modal({
						overlayId: 'modal-overlay',
						containerId: 'modal_wrap',
						closeHTML: '<div class="simplemodal-close-pad"><a href="javascript:;" class="simplemodal-close">Close</a></div>',
						opacity: 70,
						overlayClose: true,
						minWidth: 400,
						maxWidth: 600,
						minHeight: 100,
						maxHeight: 400,
						appendTo: 'body',
						onOpen: function (dialog) {
							dialog.overlay.fadeIn('slow', function () {
								dialog.data.hide();
								dialog.container.fadeIn('slow', function () {
									dialog.data.fadeIn('slow');
								});
							});
						},
						onClose: function () {
							jQuery.modal.close();
						}
					});
				}, 4000);
			}
		}
	});	
}

// ---------------------------------------------------------------------------------------
// Begin "getQueryVariable"
// getQueryVariable - looks for the first query variable. 
// If there are repeating variables in the query string, it'll return the 1st match.
function getQueryHash() {
	var hash = window.location.hash;
	if (hash != "")
		return hash;
	else
		return false;
}
// End "getQueryVariable"

// ---------------------------------------------------------------------------------------
// Begin "Initializing Tabs"
function iniTabs(parent,tabLink,tabActive,content,contentActive) {
	var parentObj = parent;
	var tabObj = tabLink;
	var tabActiveClass = tabActive;
	var contentObj = content;
	var contentActiveClass = contentActive;
	
	jQuery(tabObj).click(function(e){
		e.preventDefault();
		// Get Current Index
		var CurrIndex = jQuery(this).parents("ul:first").find("li").index(jQuery(this).parent());
		// Switch Active Tab
		jQuery(this).parents("ul:first").find("."+tabActiveClass).removeClass(tabActiveClass);
		jQuery(this).addClass(tabActiveClass);
		// Switch Active Tab Content
		jQuery(this).parents(parentObj).find("."+contentActiveClass).removeClass(contentActiveClass);
		jQuery(jQuery(this).parents(parentObj).find(contentObj).get(CurrIndex)).addClass(contentActiveClass);
	});
	
	var hashValue;
	this.checkQueryHash = function() {
		hashValue = getQueryHash();
		/* Hash trumps any server side active tab state */	
		if (hashValue && jQuery(tabObj+"[href='"+hashValue+"']").length) {
			jQuery(parent+" ul.tabs li a[href='"+hashValue+"']").click();
		}
	}
}
// End "Initializing Tabs"


/* 
End Functions
-------------------------------------------------------------------------------	*/

/* ----------------------------------------------------------------------------	
Begin "safe jQuery onload script"
*/
jQuery(document).ready(function($j) {
	if($j('#HomepageTabs').length > 0) {
		var homepageTabs = new iniTabs("#HomepageTabs","ul.tabs li a","current",".pane","active");
	}
	
	if($j('#HomeHeroRotator').length > 0) {
		$j('#HomeHeroRotator').cycle({
			timeout:10000,
			fx: 'scrollHorz',
			speed: 700,
			pager: '#HomeHeroPager',
			pagerAnchorBuilder: function(index, DOMelement)  {
				return "$('div#HomeHeroPager').append('<a href='javascript:;'>" + index + "</a>')";
			}
		});
	}

	if($j('#rotatorSpotlight').length > 0) {
		var startSlide = 0;
		var rand = 0;
		
		var industrySection = location.href.substring(location.href.indexOf('industries')+11, location.href.length-1);
		
		switch(industrySection) {
			case 'e-commerce':
				startSlide = 3;
				break;
			case 'financial-services':
				startSlide = 2;
				break;
			case 'saas-cloud':
				startSlide = 4;
				break;
			case 'arlines-hospitality':
				startSlide = 0;
				break;
			case 'online-gaming':
				startSlide = 5;
				break;
			case 'public-sector':
				startSlide = 1;
				break;
			default:
				startSlide = 0;
				rand = 1;
				break;
			
		}
		//if(location.href.indexOf('e-commerce') != -1
		
		$j('#rotatorSpotlight').cycle({
			timeout:8000,
			fx: 'scrollHorz',
			speed: 700,
			prev: '#SpotlightPrev',
			next: '#SpotlightNext',
			random: rand,
			startingSlide: startSlide
		});
	}
	
	if($j('#rotatorTour').length > 0) {
		$j('#rotatorTour').cycle({
			timeout:0,
			fx: 'scrollHorz',
			speed: 300,
			prev: '#TourPrev',
			next: '#TourNext'
		});
	}

	if($j('#rotatorPromo').children().length > 0) {
		$j('#rotatorPromo').cycle({
			timeout:8000,
			fx: 'scrollHorz',
			speed: 700,
			prev: '#PromoPrev',
			next: '#PromoNext'
		});
	}
	
	if($j('#TakeTheTour').length > 0) {
		iniTour();
		$j('#ReplayTour').live('click', function() {
			$j('#TakeTheTour').fadeOut('fast', function() {
				for(var i = 0; i < $j('#TakeTheTour').children().length; i++) {
					$j('#TakeTheTour').cycle('prev');
					if(i >=  $j('#TakeTheTour').children().length-1) {
						$j('#TakeTheTour').fadeIn('slow', function() {
							$j('#TakeTheTour').cycle('destroy');
							iniTour();
						});
					}
				}
			});
		});
	}
	
	if($j('.entry .hero_wrap').length == 0) {
		$j('#content .cols_2cols').css('background-image','none');
		//$j('#content .cols_2cols .col .main_content').css('background','url(/images/bg-hero-small.png) no-repeat scroll 10px 15px transparent');
	} else {
		$j('#content .cols_2cols .main_content').css('background-image','none');
	}
	
	if($j('.sidebar_content > span:first-child').length > 0) {
		$j('.callout_wrap:first .heading_wrap','.sidebar_content').css('margin-top','-22px');
	}
	
	
	
	var knowledgeCenterTabs = new iniTabs("#knowledgeCenterTabs","ul.tabs li a","current",".pane","activePane");
	knowledgeCenterTabs.checkQueryHash();	// check location Hash value

	var companyNewsTabs = new iniTabs("#CompanyNewsTabs","ul.tabs li a","current",".pane","activePane");
	companyNewsTabs.checkQueryHash();	// check location Hash value
	
	// ------------------------------------------------------------------------------
	// Begin "initialize setBlades"
	if ($j("#BladesMitigationProvider").length > 0) { iniBlades('.blade_title', '.blade_content', '.blade_item'); }
	// End "initialize setBlades"
	
	// ------------------------------------------------------------------------------
	// Begin "window open function for 'in the news'"
	if ($j('.news_item').length > 0) {
		$j('.news_item_link').each(function(e) {
			var _this = $j(this);
			var _parent = _this.parents('.news_item');
			
			
			 //Get the window height and width
			var windowW = $(window).width()*0.5;
			var windowH = $(window).height()*0.75;
			   var xPos = ($(window).width()*0.5) - (windowW*0.35);
			   var yPos = ($(window).height()*0.5) - (windowH*0.5) ;
			
			
			// get wordpress data values
			
			if($j('.Xpos', _parent).html() != '') {
				xPos = $j('.Xpos', _parent).html();
			}
			if($j('.Ypos', _parent).html() != '') {
				yPos = $j('.Ypos', _parent).html();
			}
			if($j('.width_window', _parent).html() != '') {
				windowW = $j('.width_window', _parent).html();
			}
			if($j('.height_window', _parent).html() != '') {
				windowH = $j('.height_window', _parent).html();
			}
			
			_this.click(function(evt) {
				evt.preventDefault();
				window.open(this.href, 'NewsItem', 'width=' + windowW + ',height=' + windowH + ',location=1,menuBar=1,resizable=1,scrollbars=1,status=0,toolbar=0,directories=0,top='+yPos+',left='+xPos);
			});
		});
	}
	
});
/* End "safe jQuery onload script" */


