﻿//flexdropdownmenu.arrowpath='../images/common/menu/menu-arrow.gif';
var emailRegEx = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
var zipcodeRegEx = /^\d{5}([\-]\d{4})?$/;
var invalidCharacterRegEx = /^\?|^\*|;|<|>|alert\s*\(|;|"|'|%/;
var _tag;

//Carrousel Functions
function initHome()
{
/*  $(".recSolutions ul").jcarousel({scroll:1});
  $(".recIndustries ul").jcarousel({scroll:1});
  $(".recProducts ul").jcarousel({scroll:1});*/
  $(".jcarousel").each(function(){
    $("ul",$(this)).jcarousel({scroll:1});
    
    
  });
  
  //$('.jcarousel').show();

  
  $(".banners .combobox").jqTransform({imgPath:'../images/controls/'});
  
  $("body").addClass("menulines_home");
  
/*  var rotatingHero = new cRotating();
  rotatingHero.idContainer = ".Testimonial";
  rotatingHero.sequenceControls = true;
  rotatingHero.nWidthControls = null;
  rotatingHero.init();*/
  
  initTabModule();
}





/*function rotator2()
{

  $(".jcarousel2").each(function(){
    $("ul",$(this)).jcarousel({scroll:1, auto: 3, wrap: 'last'});
    
    
  });

  
  
  alert('ppp')
  
}*/
  
//Product Detail Initializing
function buildControls(scFadeCircular){
  var output = '';
  var classActive = ' class="active"';
  var nTotalItems = scFadeCircular.items.length;
  
  if (nTotalItems > 1) {
    output += '<div class="controls clearfix">';
    output += '<a class="back" href="#">&lt;</a>';
    output += '<p class="size15"><span class="nItem">1</span> of '+ nTotalItems +'</p>';
    output += '<a class="next" href="#">&gt;</a>';
    output += '</div>';
  }
  
  scFadeCircular.container.append(output);

  scFadeCircular.container.delegate('.controls a', 'click', function(e){
    
    e.preventDefault();

    var lnkClass = $(this).attr('class');
    
    if(lnkClass.indexOf('back') > -1){
      scFadeCircular.prev();
    } else if (lnkClass.indexOf('next') > -1){
      scFadeCircular.next();
    }
    scFadeCircular.container.find('.controls span.nItem').html(scFadeCircular.nCurrentItem);
    
  });
}

function initFAQLanding()
{
  initExpandableModules("#contentColumn");
  var myValue = jQuery.url.setUrl(this.href).attr("anchor");

  if (myValue == null) $(".faqItem:first .handler").trigger("click");
  else
      $("#contentColumn .handler").each(function () {
          if ($(this).attr("name") == myValue) $(this).trigger("click");
      });
}

function initProductDetail()
{
  initExpandableModules("#contentColumn");
  initTabModule();
  
  $(".rotatingImages").scFadeCircular({
    controls:'noNumbers',
    delay: 0,
    initCallback: function(scFadeCircular){
      buildControls(scFadeCircular);
      scFadeCircular.showFirst();
    }
  });
  
  $(".borderRecProducts ul").jcarousel({scroll:1});
  $(".feaProducts ul").jcarousel({scroll:1});
}
function initFindDistributor()
{
  initExpandableModules("#popFindDis");
}

function initSiteSearchResults()
{
  
  $(".searchresults .current a").click(function(){
    $(this).parents(".current").hide();
    $(this).parents(".searchresults").find(".searchBox").show();
    $(this).parents(".searchresults").find(".blocker").show();
  });
  $(".searchresults .searchBox a").click(function(){
    $(this).parents(".searchBox").hide();
    $(this).parents(".searchresults").find(".blocker").hide();
    $(this).parents(".searchresults").find(".current").show();
  });
  
  $(".results").jqTransform({imgPath:'../images/controls/'});
  
  $(".searchresults .searchBox").hide();
  $(".searchresults .searchBox").css("visibility","visible");
  $(".searchresults").find(".blocker").hide();

  initTabModule();
}

function setSearchResultCounts()
{     
    $('#resourcesResultsCount').text('( ' + $('#txtResourceSearchResultsCount').val() + ' )');      
    $('#productsResultsCount').text('( ' + $('#txtProductSearchResultsCount').val() + ' )');      
    $('#siteSearchResultsCount').text('( ' + $('#txtSiteSearchResultsCount').val() + ' )');
} 

function initSubcategoryDetail()
{
  $(".rotatingImages").scFadeCircular({
    controls:'noNumbers',
    delay: 0,
    initCallback: function(scFadeCircular){
      buildControls(scFadeCircular);
      scFadeCircular.showFirst();
    }
  });
  initTabModule();
}

function onCheckGroupChange(event,group,items)
{
  if(items != null)
  {
    var sLabel = "";
    if(items.length == 1)
    {
      sLabel = items[0];
    }
    else if(items.length > 1)
    {
      sLabel = "(Multiple)";
    }
    if(sLabel.length > 12) sLabel = sLabel.substr(0, 10)+"...";
    $(group).parents(".dropdownModule").find(".label").html(sLabel);
  }
  event.stopPropagation();
}
function setCheckGroupLabel(sel)
{
  if(sel == null) sel = "";
  $(sel+" .checkgroup").bind('change',onCheckGroupChange);
}
function initCaregivers()
{
  var rotatingHero = new cRotating();
  rotatingHero.idContainer = ".Testimonial";
  rotatingHero.sequenceControls = true;
  rotatingHero.nWidthControls = null;
  rotatingHero.init();

  initTabModule();
}



/** Forms Functions **/
function disableForm(val){
    $("form input[type=submit]").attr('disabled', ((val == null) ? true : false));
}

/** Check Key down **/
function checkKey(reg, e){
    var nKey = e.which;
    var sKey = String.fromCharCode(nKey);
    if (nKey == 0 || nKey == 8 || nKey == 13) 
        return true;
    
    var re = new RegExp(reg);
    return (sKey.match(re) == null);
}

/** Auto Completition **/
function removeDuplicatedKeywords(aKeywords)
{
  aKeywords = aKeywords.sort();
  var sLast = null;
  var i = 0;
  for(i = 0; i < aKeywords.length; i++)
  {
    if(sLast != aKeywords[i]) sLast = aKeywords[i];
    else
    {
      aKeywords.splice(i,1);
      i--;
    }
  }
  return aKeywords;
}
function filterKeywords(aFilter)
{
  var aKeywords = new Array();
  if(aFilter == null || aFilter.length == 0)
  {
    for(prop in oKeywords)
    {
      aKeywords = aKeywords.concat(oKeywords[prop]);
    }
  }
  else
  {
    for(var i = 0; i < aFilter.length; i++)
    {
      if(oKeywords[aFilter[i]] != null && oKeywords[aFilter[i]].length > 0)
      {
        aKeywords = aKeywords.concat(oKeywords[aFilter[i]]);
      }
    }
  }
  return removeDuplicatedKeywords(aKeywords);
}

function setAutoComplete()
{
  var bMerge = true;
  var oList = $('.list',$(this));
  if(oList.length > 0)
  {
    oList = $(oList).html();
    oList = oList.split(",");
    bMerge = !$(oList).hasClass('merge');
  }
  else
  {
    oList = new Array();
  }
  if(bMerge)
  {
    var oFilter = $('.filter',$(this));
    if(oFilter.length > 0)
    {
      oFilter = $(oFilter).html();
      oFilter = oFilter.split(',');
    }
    else oFilter = null;
    var aKeywordList = filterKeywords(oFilter);
    oList = oList.concat(aKeywordList);
  }
  oList = removeDuplicatedKeywords(oList);
  $('input[type=text]',$(this)).autocomplete(oList, {width: 196, autoFill:true, matchContains:true, minChars:3});
}
/** END Auto Completition **/

function initSearch(sel)
{
  $(sel+' input[type=text]').keypress(function(e){
    if(e.which == 13)
    {
      $(this).parents(".item,.keywordEnterContainer").find('input[type=button]').click();
    e.stopPropagation();
      return false;
    }
    /*return checkKey(/\D/,e);*/
    return true;
  });
  $(sel).not(".initialized").each(function(){
    if($(this).find(".defaultValue").length > 0)
    {
      $('input[type=text]',$(this)).focus(function(){
        var textDefault = $(this).parents(".item").find(".defaultValue").html();
        if($(this).val() == textDefault || $(this).hasClass("required_error")){
          $(this).val("");
          $(this).removeClass("required_error");
        }
        $(this).select();
      });
      $('input[type=text]',$(this)).blur(function() {
        var textDefault = $(this).parents(".item").find(".defaultValue").html();
        if ($(this).val() == '') {
          $(this).val(textDefault);
        }
      });
      $('input[type=text]',$(this)).each(function(){
        if($(this).val() == "")
          $(this).val($(this).parents(".item").find(".defaultValue").html());
      });
    }
    else $('input[type=text]',$(this)).val("");
    $(this).addClass("initialized");
  });
  
}


function onCheckRequiredFields(obj)
{
  if(obj == null) obj = this;
  var bCheck = true;
  $(obj).parents(".requiredFields:first").find("input[type=text]").each(function(){
    var sValue = "";
    if($(this).parents(".item").find(".defaultValue").length > 0)
    {
      sValue = $(this).parents(".item").find(".defaultValue").html();
    }
    if($(this).val() == sValue || $(this).val() == "")
    {
      $(this).addClass("required_error");
      $(this).val(sRequiredError);
      bCheck = false;
    }
  });
  
  return bCheck;
}

function addRequiredHandler(buttonObj)
{
    var clickhandler = buttonObj.onclick;
      buttonObj.onclick = null;

      $(buttonObj).addClass("requiredInitialized");

      // new click handler
      $(buttonObj).click(function(ev) {


        if(onCheckRequiredFields(buttonObj))
        {
    //if(clickhandler != null)
    //{
    // clickhandler()
    //}
        }
        else
        {
       ev.stopImmediatePropagation();
       return false;
        }
      });
      
      if(clickhandler != null)
      $(buttonObj).click(clickhandler);
}

function initRequiredFields(sel)
{
  if(sel == null) sel = "";
  $(sel+" .requiredFields").find("input[type='button'],input[type='submit']").not(".requiredInitialized").each(function(){
  addRequiredHandler(this);
  
  });
}


function initExpandableModules(sel,vel)
{
  if(sel == null) sel = "";
  if(vel == null) vel = "fast";
  $(sel+" .expandableModule").not(".initialized").each(function(){
    $(".handler:first",$(this)).mouseenter(function(){$(this).toggleClass("hover")}).mouseleave(function(){$(this).toggleClass("hover")});
    $(".handler:first",$(this)).click(function(){
      $(this).parents(".expandableModule").addClass("animating");
      $(this).siblings(".content").slideToggle(vel,function(){
        $(this).parents(".expandableModule").toggleClass("open");
        $(this).parents(".expandableModule").removeClass("animating");
      });
    });
    $(this).addClass("initialized");
  });
  $(sel+" .collapseAll").click(function(){
    $(sel+" .expandableModule.open:not(.animating) .handler:first, "+sel+" .expandableModule.animating:not(.open) .handler:first").click();
  });
  $(sel+" .expandAll").click(function(){
    $(sel+" .expandableModule:not(.open):not(.animating) .handler:first, "+sel+" .expandableModule.open.animating .handler:first").click();
  });
}
function initDropDownModule(sel,vel)
{
  if(sel == null) sel = "";
  if(vel == null) vel = "fast";
  $(sel+" .dropdownModule").not(".initialized").each(function(){
    $(".handler:first",$(this)).mouseenter(function(){$(this).toggleClass("hover")}).mouseleave(function(){$(this).toggleClass("hover")});
    $(".handler:first",$(this)).click(function(){
      if($(this).parents(".dropdownModule").hasClass("animating")) return;
      $('body').unbind("click");
      $(this).parents(".dropdownModule").addClass("animating");
      $(sel+" .dropdownModule.open:not(.animating) .handler:first").click(); //Close Others
      $(this).siblings(".content").slideToggle(vel,function(){
        $(this).parents(".dropdownModule").toggleClass("open");
        $(this).parents(".dropdownModule").removeClass("animating");
        if($(this).parents(".dropdownModule").hasClass("open"))
        {
          //Add body event to close on click outside
          $('body').bind("click",function() { $(sel+" .dropdownModule.open .handler:first").click(); });
          $(this).parents(".dropdownModule").trigger("open");
        }
        else
          $(this).parents(".dropdownModule").trigger("close");
      });
    });
    $(".content:first",$(this)).hide();
    $(".content:first",$(this)).css("visibility","visible");
    $(this).addClass("initialized");
  });
  $(sel+" .dropdownModule").click(function(event){event.stopPropagation();});
}
function triggerCheckGroupChange(checkGroup)
{
  var items = new Array();
  var nOptions = $("input:checkbox[value!=all]",$(checkGroup)).length;
  var nChecked = $("input:checkbox[value!=all]:checked",$(checkGroup)).length;
  if(nOptions == nChecked) items.push("All");
  else $("input:checkbox[value!=all]:checked",$(checkGroup)).each(function(){items.push($(this).val());});
  $(checkGroup).trigger('change', [checkGroup, items]);
}
function checkGroupState(checkGroup)
{
  var nOptions = $("input:checkbox[value!=all]",$(checkGroup)).length;
  var nChecked = $("input:checkbox[value!=all]:checked",$(checkGroup)).length;
  if(nOptions == nChecked) $("input:checkbox[value=all]:not(:checked)",$(checkGroup)).attr('checked','checked');
  else $("input:checkbox[value=all]:checked",$(checkGroup)).removeAttr('checked');
  triggerCheckGroupChange(checkGroup);
}
function initCheckBoxGroup(sel)
{
  if(sel == null) sel = "";
  $(sel+" .checkgroup").not(".initialized").each(function(){
    checkGroupState($(this));
    $("input:checkbox[value!=all]",$(this)).click(function(){checkGroupState($(this).parents(".checkgroup:first"));});
    $("input:checkbox[value=all]",$(this)).click(function(){
      var checkGroup = $(this).parents(".checkgroup:first");
      if($(this).is(":checked"))
      {
        $("input:checkbox[value!=all]:not(:checked)",$(checkGroup)).attr('checked','checked');
      }
      else
      {
        $("input:checkbox[value!=all]:checked",$(checkGroup)).removeAttr('checked');
      }
      triggerCheckGroupChange(checkGroup);
    });
    $(this).addClass("initialized");
  });
}
function activateTabModule()
{
  var sTab = $(this).attr("rel");
  if(sTab != null && sTab != "")
  {
    $(this).parents(".TabModule").find(".breadcrumb,.TabControl").find("a.active").removeClass("active");
    $(this).parents(".TabModule").find(".Tab.active").fadeOut(0,function(){
      $(this).removeClass("active");
      $(this).parents(".TabModule").find(".breadcrumb,.TabControl").find("a[rel="+sTab+"]").addClass("active");
      $(this).parents(".TabModule").find(".Tab."+sTab).fadeIn(0,function(){$(this).addClass("active");});
    });
  }
}
function initTabModule(sel,callback)
{
  if(sel == null) sel = "";
  $(sel+" .TabModule").each(function(){
    $(".TabControl a:not(.disabled)",$(this)).click(activateTabModule);
    $(".breadcrumb a:not(.disabled)",$(this)).click(activateTabModule);
    $(".Tab:not(.active)",$(this)).hide();
    $(".Tab",$(this)).css("position","relative");
    $(this).css("visibility","visible");
  });
}
function initRemainingCharacters(sel)
{
  if(sel == null) sel = "";
  $(sel+" .remainingCharacters").each(function(){
    $(".textarea",$(this)).keyup(function(){
      var sVal = $(this).val();
      $(this).parents(".remainingCharacters").find(".counter").html(sVal.length);
    });
  });
}

/** FlexCombo **/
function setFlexcomboValue($obj)
{
  var sflexmenu = $obj.parents(".flexdropdownmenu").attr("id");
  $(".flexcombo a[data-flexmenu="+sflexmenu+"]:first").each(function(){
    var spanElements = $("span",$obj);
    var sLabel;
    var value = spanElements.eq(0).text();
    //var aLabel;
    if(spanElements.length > 1)
    //There is a separate value and text
       sLabel = spanElements.eq(1).text();    
    else           
       sLabel = value;    
    
    //var sLabel = $("span",$obj).html();
    //var aLabel = new Array();
    //aLabel.push(sLabel);
    
    if(sLabel.length > 20) sLabel = sLabel.substr(0, 18)+"...";
    $(this).html(sLabel);
    $obj.parents(".flexdropdownmenu").find(".label a").html(sLabel);
    $obj.parents(".flexdropdownmenu").find(".li.active").removeClass("active");
    
    //$obj.parents(".li").find("a:first span").each(function(){aLabel.unshift($(this).html())});
    $obj.parents(".li").each(function(){$(this).addClass("active");});
    $obj.parents(".li:first").addClass("active");
    //sLabel = aLabel.join(",");
    
    $(this).parents(".flexcombo:first").find("input:first").val(value);
    $(this).trigger("changed");
  });
}

function setFlexcomboDefault(sel)
{
  var $obj = $(sel).find("li a:not(.arrow)").first();
  $obj.parents("li").click();
}

function initFlexcombo(sel)
{
  if(sel == null) sel = "";
    
  $(sel+" a[data-flexmenu]").each(function(){
    var sflexmenu = $(this).attr("data-flexmenu");
    var $oflexMenu = $("#" + sflexmenu);
  
    $(".li",$oflexMenu).click(function(e){
      e.stopPropagation();
      //Disabled Link Funcionality OFF - dosorio@studiocom.com
      if($(this).hasClass("disabledLink")) return;
      //if(!$("a:first",$(this)).hasClass("arrow"))
      //{
        setFlexcomboValue($("a:first",$(this)));
        //$(this).parents("li:first").mouseleave();
        $(this).parents(".flexdropdownmenu").mouseleave();
      //}
    });
    //var sflexmenu = $(this).attr("id");
    var sSelectedVal = $(this).parents(".flexcombo:first").find("input:first").val();
    
    if(sSelectedVal == null || sSelectedVal == "")
    {
      if($("a.preselected",$(this)).length > 0)
        $("a.preselected:first",$(this)).click();
      else
        $(".label a:first",$(this)).click(function(){$(this).parents(".flexdropdownmenu").mouseleave();});
    }
    else
    {
      //var aSelectedVal = sSelectedVal.split(",");
      var $targetObj = $oflexMenu;
      var bFound = true;
      //for(var i = 0; bFound && i < aSelectedVal.length; i++)
      //{
        bFound = false;
        $(".flexdropcontent>.li>a>span",$oflexMenu).each(function(){
          if(!bFound) {
            if($(this).html() == sSelectedVal) //aSelectedVal[i])
            {
              bFound = true;
              $targetObj = $(this).parents(".li:first");
            }
          }
        });
        if(bFound)
        {
          $("a:first",$targetObj).click();
        }
      //}
    }
    
  });
  $(sel+" .flexdropdownmenu").click(function(e){
    e.stopPropagation();
  });
}
/** END FlexCombo **/


/**Show-Hide detail Box**/
function iniBoxDetail(){
  initTooltipModule();
}

function initTooltipModule(sel){
  if(sel == null) sel = "";
  $(sel+" .toolTipModule:not(.disabled)").each(function(){
    $(this).mouseenter(function(){
      if(jQuery.browser.msie)
        $(".toolTipBox", $(this)).toggle();
      else
        $(".toolTipBox", $(this)).fadeToggle();  
        });
     $(this).mouseleave(function(){    
       if(jQuery.browser.msie)
              $(".toolTipBox", $(this)).toggle();
      else
        $(".toolTipBox", $(this)).fadeToggle();  
     });
  });
  
}


function iniBubbleBox(){
  initBubbleModule();
}

function initBubbleModule(sel){
  if(sel == null) sel = "";
  $(sel+" .moreLink:not(.disabled)").each(function(){
    $(this).mouseenter(function(){
      var marginT = ( -($(".categoryBubble", $(this)).height()+12) );
      $(".categoryBubble", $(this)).css({ marginTop: marginT });
      $(".categoryBubble", $(this)).fadeToggle();  
        });
     $(this).mouseleave(function(){
      $(".categoryBubble", $(this)).fadeToggle();
     });
  });
  
}

function ltrim(str) { 
	for(var k = 0; k < str.length && isWhitespace(str.charAt(k)); k++);
	return str.substring(k, str.length);
}
function rtrim(str) {
	for(var j=str.length-1; j>=0 && isWhitespace(str.charAt(j)) ; j--) ;
	return str.substring(0,j+1);
}
function trim(str) {
	return ltrim(rtrim(str));
}
function isWhitespace(charToCheck) {
	var whitespaceChars = " \t\n\r\f";
	return (whitespaceChars.indexOf(charToCheck) != -1);
}

function submitKeywordSearch(inputName, url, blnNewWindow)
{
  //alert(url + $('[name=' + inputName + ']').val())
  //var inputclean = ltrim(rtrim(inputName));
    if(invalidCharacterRegEx.test($('[name=' + inputName + ']').val())){
        $(".searchBox").find(".formInputError").css("display","block");
    }
    else{
        if(blnNewWindow)
        window.open(url + trim($('[name=' + inputName + ']').val()));
        else
        window.location = url + trim($('[name=' + trim(inputName) + ']').val());
        return false;
    }
}

function checkProductFinderEnabled()
{
  var finderModule = $(this).parents(".dropdownModule");
  if(finderModule.hasClass("open"))
  //Only do search on change when open
  {
    doFinderSearch(finderModule);
  }  
}

function inputClearField(sel){
    var input = $(sel).find('input[type=text]');
    input.val("");
}

function inputHasInvalidCharacters(sel)
{
    var input = $(sel).find('input[type=text]');
    if(!invalidCharacterRegEx.test(input.val())){
        $(sel).find(".formInputError").css("display","none");
        return true;
    }
    else{
        $(sel).find(".formInputError").css("display","block");
        return false;
    }
}

function initFilterResult(){
  initSearch(".filterBox .input.item");
  $(".filterBox").jqTransform({imgPath:'../images/controls/'});    
  $(".combobox").jqTransform({imgPath:'../images/controls/'});
}
function onProductFinderOpen(){
  
  //$("select",$(this)).jqSelectedIndex(0);
  //setFlexcomboDefault("#"+$(".flexmenu",$(this)).attr("data-flexmenu"));
  if(!$(this).hasClass("loaded"))
  {       
      $(this).addClass("loaded");
      doFinderSearch($(this));
  }
}

function doFinderSearch(finderObj)
{
  if(finderObj.hasClass("productfinder"))
    performProductFinderSearch();
  else 
    performResourceFinderSearch();  
}

function validateTextboxInput(source, args)
{
  var txtInput = $("#" + source.controltovalidate);
  var blnHasFormatError = false;
      
  if((args.Value == "" || args.Value == source.errormessage) && !source.fieldNotRequired)
  {
    
    txtInput.val(source.errormessage);
    txtInput.addClass("required_error");
    args.IsValid = false;      
  }  
  else    
    txtInput.removeClass("required_error");        
  
  
  if(args.IsValid && (!source.fieldNotRequired || (source.fieldNotRequired && args.Value != "")))
  {  
    var errorMessage = "";
    if(source.validationRegEx && !new RegExp(source.validationRegEx).test(args.Value))
    {
      errorMessage = source.validationRegExErrorMessage;
      args.IsValid = false;
    }
    
    if(invalidCharacterRegEx.test(args.Value))
    {
       if(errorMessage != "")
         errorMessage += "<br />";
         
       errorMessage += invalidCharactersMessage;
       args.IsValid = false;
    }
    
    if(!args.IsValid)
    {
      var inputErrorContainer = txtInput.parents(".TextsContainer:first").find(".formInputError");
      inputErrorContainer.html(errorMessage);
      inputErrorContainer.css("display","block");
      args.IsValid = false;
      txtInput.addClass("required_error");
    }
  }
  
  if(args.IsValid)
    txtInput.parents(".TextsContainer:first").find(".formInputError").css("display","none");
  
}

function clearASPNetValidationRequiredKeyword()
{
  $(this).removeClass("required_error");
  $(this).parents(".TextsContainer:first").find(".formInputError").css("display","none");
  for(var x=0;x < Page_Validators.length;x++)
  {
       if(Page_Validators[x].controltovalidate == $(this).attr("id"))
       {
            if($(this).val() == Page_Validators[x].errormessage)            
                 $(this).val("");                 
                        
            break;
       }
  }
}

function showPopupInformation(id)
{  
  var popup = $("#" + id);
  
  popup.find("input[type=text]").val("").trigger("blur");
    
  popup.css("display","block");
}

function closePopupInformation(id)
{
  $("#" + id).css("display","none");
}


function closePopupMedia(id)
{
  displayResourceMedia("","");
  displayResourceMediaVideo("","");
  $("#" + id).css("display","none");
}

function addEmailRecipient()
{
  var strEmailAddress = $.trim($("#txtEmailRecipientToAdd").val());
  var errorAlreadyAdded = $("#arAlreadyAdded");
  var errorEmailRequired = $("#arEmailRequired");
  var errorInvalidEmailFormat = $("#arInvalidEmailFormat");

  errorAlreadyAdded.css("display","none");
  errorEmailRequired.css("display","none");
  errorInvalidEmailFormat.css("display","none");
  
  var recipientsContainer = $("#recipients");
  $("#txtEmailRecipientToAdd").focus();
  
  if(strEmailAddress == "")
  {    
    errorEmailRequired.css("display","inline");
    return;
  }
  if(recipientsContainer.find("input[value='" + strEmailAddress + "']").length > 0)
  {
    errorAlreadyAdded.css("display","inline");
    
    var addedEmailEle = $("#arAlreadyAddedEmailAddress");
    addedEmailEle.css("display","inline");
    addedEmailEle.text(strEmailAddress);
    $("#txtEmailRecipientToAdd").val("");
        
    return;
  }
  if(!emailRegEx.test(strEmailAddress))
  {    
    errorInvalidEmailFormat.css("display","inline");
    return;
  }
  
  
  var html = "<div class=\"Recipient\">";
  html += ", <span class=\"RecipientBlue\">" + strEmailAddress + "</span> <input type=\"hidden\" name=\"recipient[]\" value=\"" + strEmailAddress + "\" /> <a href=\"javascript:void(0)\"><img src=\"/images/common/delete-icon-small.png\" alt=\"Remove\"/></a>";
        html += "</div> ";
        
        recipientsContainer.append(html);
        $("#txtEmailRecipientToAdd").val("");
        

}

function removeEmailRecipient()
{
  $(this).parents(".Recipient:first").remove();
}


function initializeFinderModule(sel){
  if(sel == null) sel = ".finderModule";
  if($(sel).length <= 0) return;
  $(sel+" select").bind("changed",checkProductFinderEnabled);
  //$(sel).bind("close",onProductFinderOpen);
  $(sel).bind("open",onProductFinderOpen);
  $(sel+" .finder_category .flexmenu").bind("changed",checkProductFinderEnabled);
  initSearch(sel+" .input.item");
  initFlexcombo(sel+" .finder_category");
  $(sel+" .combobox").jqTransform({imgPath:'../images/controls/'});
  $(sel).css("visibility","visible");
}
function accordionDistributors(){
  $('.distItem .distItemContent.content').hide();
  $('.distItem a.handler:first')
    .addClass('active')
    .next()
    .show();

  $('.distItem a.handler').click(function(){
    if( $(this).next().is(':hidden') ) {
      $('.distItem a.handler')
        .removeClass('active')
        .next()
        .slideUp();
      $(this).toggleClass('active')
        .next()
        .slideDown();
      }
    return false;
  });  
}

//Handles z-index bug in IE7 regarding resource finder getting covered up by featured solution masked image
function handleResourceFinderIEDisplayBug()
{
  if(typeof isResourceLandingPage != "undefined" && navigator.appVersion.indexOf("MSIE 7.") != -1)
  {
    var featuredAnchors = $("#sideColumn .callout .content a");
    
    featuredAnchors.each(function(){
      $(this).find("span.mask").css("display","none");
    });
    
    featuredAnchors.css("position","static");
  }
}

$(document).ready(function(){
  //accordion
  
  
  
  //FANCYBOX

      /*$("#howPurchase").fancybox({
        'overlayColor'    : '#fff',
        'overlayOpacity'  : 0.7,
        'width'        : 530,
        'height'      : 278,
        'autoScale'       : true,
             'transitionIn'    : 'none',
        'transitionOut'    : 'none',
        'type'        : 'iframe'
      });*/
  
  
  //initInvalidCharacterValidation(".searchBox .item input[type=button],.productfinder input[type=button],.resourcefinder input[type=button],.keywordEnterContainer input[type=button],.popupInformationContainer .formFindDis input[type=button],#popFindDis .keywordEnterContainer input[type=button]");
    
  initRequiredFields();
  
  initSearch(".searchBox .item");
  initSearch(".popupInformationBox .item");  
  initSearch(".recipientBox .item");  
               
  $(".resourceTypeQVLink").bind("click",displayResourceTypeQuickView);
  
  $(".FormContent .TextsContainer .input input,.FormContent .TextsContainer .inputLarge textarea").bind("focus",clearASPNetValidationRequiredKeyword);
      $(".FormContent .TextsContainer .input input,.FormContent .TextsContainer .inputLarge textarea").bind("blur",function(e){ $(this).trigger("change"); e.stopPropagation(); });
   
//************************WEB TRENDS INITIALIZATION***********************
//   setBreadcrumbMeta();
//  _tag=new WebTrends();
//  _tag.dcsGetId();
//  _tag.dcsCustom=function(){
//   Add custom parameters here.
//  _tag.DCSext.param_name=param_value;
//  }
//  _tag.dcsCollect();
//************************END WEB TRENDS INITIALIZATION***********************
     
     handleResourceFinderIEDisplayBug();
     
  /** Email Validation Field **/
    $(".email").keypress(function(e){
        return checkKey(/[^\w.@_-]/, e);
    });
  /** Name Validation Field **/
/*    $(".name_field").keypress(function(e){
        return checkKey(/[^a-zA-Z\s'.-]/, e);
    });*/
  /** Init DropDown Modules **/
  initDropDownModule();
  /** Product Finder **/
  initializeFinderModule(".productfinder");
  initializeFinderModule(".resourcefinder");

      
  $(".combobox").jqTransform({imgPath:'../images/controls/'});
  $(".subCategory .filterBox").jqTransform({imgPath:'../images/controls/'});
  $(".check_box").jqTransform({imgPath:'../images/controls/'});
    
  $(".siteSearchAutocomplete, #txtSiteSearchNewSearch").autocomplete({
        source: function( request, response )
        {
          $.ajax({
      url: "/umbraco/search/AutocompleteHandler.ashx",
      dataType: "json",
      data: {                     
        r_keyword: request.term,
        searchType: 'site',
                currentPageURL: window.location.hostname
      },
      type: "POST",
      success: function( data )
      {
        response(data);
      }
          });
        },
        minLength: 2,
         open: function(event, ui)
         { $('.ui-autocomplete').css('zIndex', '100000');    }  
      });
  
//  $(".filterBox.combobox").jqTransform({imgPath:'../images/controls/'});
  
  
  if($(this).jScrollPane != null)
    $('.scroll-pane').each(function(){$(this).jScrollPane({scrollbarWidth: 22,animateTo:true, animateInterval:50, animateStep:5,arrowSize:15,showArrows:true });});

//  $(".productfinder").css("visibility","visible");

  //initSymbolReplacement();
});
/*
function initSymbolReplacement(element)
{
    var tagToCheck = 'div,li,td';
    if($.browser.msie && $.browser.version == '7.0'){
        tagToCheck = 'div,li';
    }

    $(tagToCheck).each(function(){
        if(!$(this).has('img').length)
        {
            if($(this).text().indexOf('®') != -1)
            $(this).html($(this).html().replace(/®/g,"<sup style='height: 1; line-height: 1; vertical-align: baseline; _vertical-align: bottom; position: relative; bottom: 0.3em;'>&reg;</sup>"));
        }
    });
}
*/

//*****************************AJAX Product/Resource Finder Methods
function showAJAXWait()
{
  $("#AJAXWaitContainer").css('display', 'block');
}

function clearAJAXWait()
{
     clearTimeout(ajaxTimer);
     $("#AJAXWaitContainer").css('display', 'none');
}

function ajaxSearchPageLoaded(sender, args) 
{
  initFilterResult();
}

 function populateDropdown(dropdownObj, selectValues) {
         
         dropdownObj.empty();
         for (var i = 0; i < selectValues.length; i++) 
         {     
             var strDisabledAttr = "";
             if(selectValues[i].Key.indexOf("-") == 0)
               strDisabledAttr = "disabled=\"disabled\"";
               
             dropdownObj.append("<option " + strDisabledAttr + " value=\"" + selectValues[i].Key + "\">" + selectValues[i].Value + "</option>");
         }
     }
     
 function performResourceFinderSearch() {    
     var typeFilter = $("#ResourceTypeContainer");
     var typeSelectedValue = typeFilter.val();
     var resource_productCategorySelectedValue = $("#rf_category").val();
     var industrySelectedValue = $("#rf_Industry").val();
     
     var keywordInputObj = $("#ResourceFinderKeyword");
     var keywords = keywordInputObj.val();
     var defaultKeyword = keywordInputObj.parents(".item:first").find(".defaultValue").text();

     if(keywords == defaultKeyword)
  keywords = "";
     
     ajaxTimer = setTimeout(showAJAXWait, 200);
     
     jQuery.ajax({
         url: "/umbraco/search/FinderHandler.ashx",
         dataType: "json",
         data: {
             finderType: 'resource',
             rfTypeFilter: typeSelectedValue,
             rfCategoryFilter: resource_productCategorySelectedValue,
             rfIndustryFilter:industrySelectedValue,
             rf_TypeParentID: $("#rf_TypeParentID").val(),
             rf_CategoriesParentID: $("#rf_CategoriesParentID").val(),
             rf_IndustriesParentID: $("#rf_IndustriesParentID").val(),
             keyword: keywords,
             currentPageURL: window.location.hostname,
             rfTypePrompt: $("#rfTypePrompt").val(),
       rfCategoriesPrompt: $("#rfCategoriesPrompt").val(),
             rfIndustriesPrompt: $("#rfIndustriesPrompt").val()
         },
         type: "POST",
         success: function(data) {
             populateDropdown(typeFilter, data.resourcetypes);
             typeFilter.val(typeSelectedValue);
             typeFilter.jqUpdateSelect();
             $("#rfmatchingResults").text(data.rfmatchingResults);
             buildFlexMenu('ResourceCategoryContainer', data.productCategories, resource_productCategorySelectedValue);
             buildFlexMenu('ResourceIndustriesContainer', data.industries, industrySelectedValue);
                             
             initFlexcombo(".resourcefinder .finder_category");
             
             $(".resourcefinder .finder_category .flexmenu").bind("changed",checkProductFinderEnabled);
             
             clearAJAXWait();
         }
     });  
      
 }
     
 function performProductFinderSearch() {
         var brandFilter = $("#productFinderBrandFilter");
         var brandSelectedValue = brandFilter.val();
         var productCategorySelectedValue = $("#productfinder_category").val();
         var industrySelectedValue = $("#pfIndustry").val();
         var keywordInputObj = $("#productFinderKeyword");
         var keywords = keywordInputObj.val();
         var defaultKeyword = keywordInputObj.parents(".item:first").find(".defaultValue").text();
         
         if(keywords == defaultKeyword)
           keywords = "";
         
         ajaxTimer = setTimeout(showAJAXWait, 200);
         
         jQuery.ajax({
             url: "/umbraco/search/FinderHandler.ashx",
             dataType: "json",
             data: {
                 finderType: 'product',
                 pfBrandFilter: brandSelectedValue,
                 pfCategoryFilter: productCategorySelectedValue,
                 pfIndustryFilter:industrySelectedValue,
                 pfBrandsParentID: $("#pfBrandsParentID").val(),
                 pfProductCategoriesParentID: $("#pfProductCategoriesParentID").val(),
                 pfIndustriesParentID: $("#pfIndustriesParentID").val(),
                 keyword: keywords,
             currentPageURL: window.location.hostname,
             pfBrandsPrompt: $("#pfBrandsPrompt").val(),
             pfCategoriesPrompt: $("#pfCategoriesPrompt").val(),
             pfIndustriesPrompt: $("#pfIndustriesPrompt").val()
             },
             type: "POST",
             success: function(data) {              
                 populateDropdown(brandFilter, data.brands);
                 brandFilter.val(brandSelectedValue);
                 brandFilter.jqUpdateSelect();
                 $("#pfMatchingResults").text(data.matchingResults);
 
                 buildFlexMenu('pfCategoryContainer', data.productCategories, productCategorySelectedValue);
                 buildFlexMenu('pfIndustriesContainer', data.industries, industrySelectedValue);
                                 
                 initFlexcombo(".productfinder .finder_category");
                 
                 $(".productfinder .finder_category .flexmenu").bind("changed",checkProductFinderEnabled);
                 
                 clearAJAXWait();
             }
         });
     }
     
    function submitResourceFinderSearch(pfResultsPageURL)
    {
      var typeSelectedValue = $("#ResourceTypeContainer").val();
      var productCategorySelectedValue = $("#rf_category").val();
      var industrySelectedValue = $("#rf_Industry").val();
      var typesParentID = $("#rf_TypeParentID").val();
      var productCategoriesParentID = $("#rf_CategoriesParentID").val();
      var industriesParentID = $("#rf_IndustriesParentID").val();
      var keyword = $("#ResourceFinderKeyword").val();
  
      var queryString = "?tf=" + typeSelectedValue + "&rcf=" + productCategorySelectedValue + "&if=" + industrySelectedValue + "&trid=" + typesParentID + "&rcpid=" + productCategoriesParentID + "&ipid=" + industriesParentID + "&keyword=" + keyword;
  
        if(!invalidCharacterRegEx.test(keyword)){
            window.location = pfResultsPageURL + queryString;
        }
        else{
            $("#formInputError").css("display","block");
        }
    }
     
     function submitProductFinderSearch(pfResultsPageURL)
     {
        var brandSelectedValue = $("#productFinderBrandFilter").val();
        var productCategorySelectedValue = $("#productfinder_category").val();
        var industrySelectedValue = $("#pfIndustry").val();
        var brandsParentID = $("#pfBrandsParentID").val();
        var productCategoriesParentID = $("#pfProductCategoriesParentID").val();
        var industriesParentID = $("#pfIndustriesParentID").val();
        var keyword = $("#productFinderKeyword").val();

        var queryString = "?bf=" + brandSelectedValue + "&pcf=" + productCategorySelectedValue + "&if=" + industrySelectedValue + "&bpid=" + brandsParentID + "&pcpid=" + productCategoriesParentID + "&ipid=" + industriesParentID + "&keyword=" + keyword;
         
        if(!invalidCharacterRegEx.test(keyword)){
            window.location = pfResultsPageURL + queryString;
        }
        else{
            $(".productfindererrorcontainer").find(".formInputError").css("display","block");
        }
     }
     
     
        function buildFlexMenu(containerID, treeData, selectedValue)
     {
         var flexMenuContainer = $('#' + containerID);
                 
         flexMenuContainer.children("input[type='hidden']").val(selectedValue);
         
         var flexMenu =  flexMenuContainer.children('a.flexmenu');
         var ulFlexID = flexMenu.attr('data-flexmenu');
         //flexMenu.text(selectedText);
         
         var flexMenuUL = $('#' + ulFlexID);              
                 
 
     var menuHTML = "<div class=\"finder_category label\"><a href=\"javascript:void(0);\" class=\"flexmenu\"></a></div>";
     menuHTML += "<div class=\"top\"></div>";
     menuHTML += "<div class=\"flexdropcontent\">";
     menuHTML += getFlexMenuItemsByParent("topLevel", treeData, selectedValue);  

     //flexMenu.text(selectedText);
     $(".li",flexMenuUL).unbind();
     flexMenuUL.empty();
     flexMenuUL.append(menuHTML);
     flexMenu.unbind();
     flexdropdownmenu.builtflexmenuids = jQuery.grep(flexdropdownmenu.builtflexmenuids, function(a) { return a != ulFlexID; });

     flexMenu.addflexmenu(ulFlexID);
     }
     
     function getFlexMenuItemsByParent(strParentID, treeData, selectedValue) {
         if (treeData[strParentID] == null)
             return "";
             
         var dataLength = treeData[strParentID].length;
         if(dataLength == 0)
             return "";
             
         var strHTML = "";
         
         if(strParentID != "topLevel") //Containing UL has not been created yet
         {
             strHTML += "<div class=\"ul clearfix\">";
       strHTML += "<div class=\"top\"></div>";
       strHTML += "<div class=\"flexdropcontent\">";
     }                  
              
         for(var x=0;x < dataLength;x++)
         {
             var classText = "class=\"li";
             
             if (x == 0)
                 classText += " first";
             if ((x+1) == dataLength)
                 classText += " last";
 
             if (treeData[strParentID][x].Key == selectedValue)            
                 classText += " active";
             else if (treeData[strParentID][x].Key.indexOf("-") == 0) //Contains no results
               classText += " disabledLink";
             
             classText += "\"";
 
        strHTML += "<div " + classText + "><a href=\"javascript:void(0);\"><span class=\"hiddenValue\">" + treeData[strParentID][x].Key + "</span><span>" + treeData[strParentID][x].Value + "</span></a>";
       strHTML += getFlexMenuItemsByParent(treeData[strParentID][x].Key, treeData, selectedValue);
             strHTML += "</div>";
         }
         
         strHTML += "</div>";
       strHTML += "<div class=\"bottom\"></div>";
     
        if(strParentID != "topLevel")
         strHTML += "</div>";
         
         return strHTML;
     }     
     
function resourceFinderResultsPageLoaded(sender, args) 
 {
   var typeFilter = $("#rfrTypeFilter");
   populateDropdown(typeFilter, resourceFinderResultData.resourcetypes);
   typeFilter.val(resourceFinderResultData.typeSelectedValue);
   typeFilter.jqUpdateSelect();
   
   buildFlexMenu('rfrCategoryContainer', resourceFinderResultData.productCategories, resourceFinderResultData.resourceCategorySelectedValue);
   buildFlexMenu('rfrIndustriesContainer', resourceFinderResultData.industries, resourceFinderResultData.industrySelectedValue);
 
   initFlexcombo(".resourceFinderRes .finder_category");
        $(".resourceFinderRes .finder_category .flexmenu").bind("changed",finderResultsPageFilterChanged);  
 }  
 
 function productFinderResultsPageLoaded(sender, args) 
 {
   var brandFilter = $("#pfrBrandFilter");
   populateDropdown(brandFilter, productFinderResultData.brands);
   brandFilter.val(productFinderResultData.brandSelectedValue);
   brandFilter.jqUpdateSelect();
   
   buildFlexMenu('pfrCategoryContainer', productFinderResultData.productCategories, productFinderResultData.productCategorySelectedValue);
   buildFlexMenu('pfrIndustriesContainer', productFinderResultData.industries, productFinderResultData.industrySelectedValue);
 
   initFlexcombo(".productFinderRes .finder_category");
        $(".productFinderRes .finder_category .flexmenu").bind("changed",finderResultsPageFilterChanged);  
 }   
 
 function finderResultsPageFilterChanged()
 {
   var filterBox = $(this).parents(".filterBox").find(":button:first").trigger("click");
 }
        
         
  function aspNETAJAXEndRequest(sender, args)
  {
  var debugMode = true;
     window.status = "Done";
     document.body.style.cursor = "default";
     
     var topPagingElement = $(".topPaginator:visible:first");
     if (topPagingElement.length > 0)
     {
  var offset = topPagingElement.offset();
  window.scrollTo(offset.left, offset.top);
     }
      
     if (args.get_error() != undefined) //error occurred
     {
         var errorMessage = "An error occurred communicating with the server. Please try again.";
         
         if(debugMode)
         {
              errorMessage = args.get_error().message;        
               alert(errorMessage);
         }
              
          args.set_errorHandled(true);
      }
}

function updateMyProductListRequestSample()
{
  $.post('/umbraco/search/MyProductListHandler.ashx', 
    { productID: $(this).val(), requestSample: this.checked, isUpdate:true },
    function(data)   {  },
  "json");
}

function addToMyProductList(strProductID, strProductName, blnRequestSample)
{
  $.post('/umbraco/search/MyProductListHandler.ashx', 
  { productID: strProductID, requestSample: blnRequestSample},
  function(data) 
  {
      $("#mplProductName").text(strProductName);
      
      
      if(data["productAdded"])
      {
        $("#mplWasAdded").css("display","inline");
    $("#mplAlreadyExists").css("display","none");
      }
      else
      {
        $("#mplWasAdded").css("display","none");
    $("#mplAlreadyExists").css("display","inline");
      }
      
      showPopupInformation("addedToMyProductList");
  },
  "json");

} 


function displayResourceTypeQuickView()
{
  var typeFilterRegEx = /tf=\d+/;
  var popup = $("#resourceQuickViewPopup");
  
  var resourceTypeID = $(this).find("span.hiddenValue").text();
  
  ajaxTimer = setTimeout(showAJAXWait, 200);
  
  $.post('/umbraco/search/FinderHandler.ashx', 
    { finderType: "resourceTypeQV", 
      typeID: resourceTypeID,
      currentPageURL: window.location.hostname },
    function(data) 
    {
              popup.find(".resourceTypeQVHeader").text(data.resourceQVTypeName);
              popup.find(".resourceTypeQVDescription").text(data.resourceQVTypeDescription);
        
              var resourcesContainer = popup.find("#resourceTypeQVResources");
              var resourcesNotFoundContainer = popup.find("#resourceTypeQVNoneFound");    
        var seeAllAnchor = $("#resourceTypeQVSeeAll");
        var recentHeading = popup.find(".resourceTypeQVRecentHeading");
        
        if(data.resourceQVData.length > 0)
        {
          seeAllAnchor.css("display","block");
          resourcesContainer.css("display","block");
          resourcesNotFoundContainer.css("display","none");
          recentHeading.css("display","block");

          seeAllAnchor.find("span").text(data.resourceQVTypeName);

          var seeAllHref = seeAllAnchor.attr("href");
          seeAllAnchor.attr("href",seeAllHref.replace(typeFilterRegEx,"tf=" + resourceTypeID));
          
          recentHeading.find("span").text(data.resourceQVTypeName);

          var tbody = popup.find("tbody");
          tbody.empty();

          for(var x=0;x < data.resourceQVData.length;x++)
          {
          var tableRowHTML = "<tr>\r\n";
          
          var target = "_blank";
            
          if ( data.resourceQVData[x].IsMedia == true)
            {
              target = "_self";
            }
            if(data.resourceQVData[x].TypeFile == "IMG") {
                tableRowHTML += "\t<td><a href=\"javascript:closePopupInformation('resourceQuickViewPopup');displayResourceMedia('" + data.resourceQVData[x].AssetURL + "','"+data.resourceQVData[x].TypeFile+"')\" class=\"nameText\">" +  data.resourceQVData[x].Title  + "</a></td>\r\n";
            }
            else if(data.resourceQVData[x].TypeFile == "SWF"){
                tableRowHTML += "\t<td><a href=\"javascript:closePopupInformation('resourceQuickViewPopup');displayResourceMedia('" + data.resourceQVData[x].AssetURL + "','"+data.resourceQVData[x].TypeFile+"')\" class=\"nameText\">" +  data.resourceQVData[x].Title  + "</a></td>\r\n";
            }
            else if(data.resourceQVData[x].TypeFile == "FLV"){
                tableRowHTML += "\t<td><a href=\"javascript:closePopupInformation('resourceQuickViewPopup');displayResourceMediaVideo('" + data.resourceQVData[x].AssetURL + "','"+data.resourceQVData[x].TypeFile+"')\" class=\"nameText\">" +  data.resourceQVData[x].Title  + "</a></td>\r\n";
            }            
            else{
              tableRowHTML += "\t<td><a href=\"" + data.resourceQVData[x].AssetURL + "\" target=\"" + target + "\">" +  data.resourceQVData[x].Title  + "</a></td>\r\n";
            }
            tableRowHTML += "\t<td><img src=\"" + data.resourceQVData[x].ImageURL + "\" alt=\"\"/></td>\r\n";
            tableRowHTML += "\t<td>" + data.resourceQVData[x].FileSize  + "</td>\r\n";
            tableRowHTML += "\t<td>" + data.resourceQVData[x].Language  + "</td>\r\n";
            tableRowHTML += "\t<td>" + data.resourceQVData[x].DatePosted  + "</td>\r\n";
            tableRowHTML += "</tr>"
    
            tbody.append(tableRowHTML);               
          }
               }
               else
               {
       seeAllAnchor.css("display","none");
       resourcesContainer.css("display","none");
       resourcesNotFoundContainer.css("display","table-cell");
       resourcesNotFoundContainer.find("span").text(data.resourceQVTypeName);
       recentHeading.css("display","none");
               }
               
               clearAJAXWait();
        
        popup.css("display","block");
    },
  "json");
  
  
}



$(function () {
    var tabContainers = $('div.tabs > div');
    
    $('div.tabs ul.tabNavigation a').click(function () {
        tabContainers.hide().filter(this.hash).show();
        
        $('div.tabs ul.tabNavigation a').removeClass('selected');
        $(this).addClass('selected');
        
        return false;
    }).filter(':first').click();
});


function displayResourceMedia(url, type)
{
  var popup = $("#ResourcesPreviewMedia");
  var content = $("#ResourcesMediaContent");
  popup.css("display","block");
  content.html("");
  content.css("margin","0 auto");
  content.css("width","500px");
  content.css("height","500px");
  if(type == "IMG"){
    var img = document.createElement("IMG");
    img.src = url;
    img.width = 500;
    content.append(img);
  }
  else if(type == "SWF"){
      var divswf = document.createElement("DIV");
      divswf.setAttribute("id","flashContent") ;
      content.append(divswf);
      var swfVersionStr = "10.1.52";
      var xiSwfUrlStr = "";
      var flashvars = {};
      var params = {};
      params.quality = "high";
      params.bgcolor = "#ffffff";
      params.play = "true";
      params.loop = "false";
      params.wmode = "window";
      params.scale = "showall";
      params.menu = "true";
      params.devicefont = "false";
      params.salign = "";
      params.allowscriptaccess = "sameDomain";
      var attributes = {};
      attributes.id = "videoPlayer";
      attributes.name = "videoPlayer";
      attributes.align = "middle";
      swfobject.embedSWF(
        url, "flashContent",
        "500", "100%",
        swfVersionStr, xiSwfUrlStr,
        flashvars, params, attributes);
  }
}

function displayResourceMediaVideo(url, type)
{
  var popup = $("#ResourcesPreviewMedia");
  var content = $("#ResourcesMediaContent");
  popup.css("display","block");
  content.html("");
  content.css("margin","0 auto");
  content.css("width","500px");
  content.css("height","500px");
  
  if(type == "FLV"){
      var divswf = document.createElement("DIV");
      divswf.setAttribute("id","flashContent") ;
      content.append(divswf);
      var swfVersionStr = "10.1.52";
      <!-- xiSwfUrlStr can be used to define an express installer SWF. -->
      var xiSwfUrlStr = "";
      var flashvars = {};
      //flashvars.videoPath="http://www.youtube.com/v/RAArPLF0oNc?fs=1&hl=en_US";
      //flashvars.videoPath="tvc.flv";
      flashvars.videoPath=url;
      var params = {};
      params.quality = "high";
      params.bgcolor = "#ffffff";
      params.play = "true";
      params.loop = "true";
      params.wmode = "window";
      params.scale = "showall";
      params.menu = "true";
      params.devicefont = "false";
      params.salign = "";
      params.allowscriptaccess = "sameDomain";
      var attributes = {};
      attributes.id = "videoPlayer";
      attributes.name = "videoPlayer";
      attributes.align = "middle";
      swfobject.embedSWF(
        "/swf/videoPlayer.swf", "flashContent",
        "500", "100%",
        swfVersionStr, xiSwfUrlStr,
        flashvars, params, attributes);
  }
}

/**************************************************************************BEGIN WEB TRENDS FUNCTIONS*********************************************************************************************************************/
var meta_cg_n = "";
var meta_cg_s = "";

function updateCgGrp(ncg_n, ncg_s)
{
  meta_cg_n = _tag.WT.cg_n;
   meta_cg_s = _tag.WT.cg_s;
  _tag.WT.cg_n = ncg_n;
  _tag.WT.cg_s = ncg_s;
}

function revertCgGrp()
{
  _tag.WT.cg_n = meta_cg_n;
  _tag.WT.cg_s = meta_cg_s;
}


function updateContactMetaInfo()
{
    _tag.WT.si_x = "1";
}

function setBreadcrumbMeta()
{
     var breadcrumbs = $('#breadcrumb li');
   
  if(breadcrumbs.length > 0)
     {     
    var breadcrumbString = "";

    $('#breadcrumb li').each(function (index) {
      if(index > 0)
         breadcrumbString += ",";

      var anchorEle = $(this).find("a");
      if(anchorEle.length > 0)
        breadcrumbString += anchorEle.text();
      else
        breadcrumbString += $(this).text();  

    });

    $('meta[name=WT.z_BreadcrumbDrilldown]').attr('content',breadcrumbString);
  }
}

function setContactUSSubmittedMeta()
{
  $('meta[name=WT.si_x]').attr('content','2');
  $('meta[name=WT.si_cs]').attr('content','1');
  _tag.dcsCollect();
}

/**************************************************************************END WEB TRENDS FUNCTIONS***********************************************************************************************************************/
