/*Global and configurable variables. */
var activeVideoId = "1001";
var activeCategoryName = "Why CenturyLink";
var defaultTemplateHt = "420";
var altTemplateHt = "560";
var isPlaying = false;  
var flashTitle;
var thumbsPerSlide = 5;/*change the 'defaultTemplateHt' (currently 335 for 4) and 'altTemplateHt' values accordingly */
var minLength = 54;/* Number of letters before adding "..." to the video title */
var ellipsisMark = "..." ;
var slideSpeed = 300;/*enter a value in milliseconds */
var lastAction = ""; /*updated by the Flash player with whatever action was the last */
var openInNewWin = ["3014","1005"];
var assetMetricsPath = "/business/storeMetricForAsset.ajax"; 

/** Code below needn't be modified **/
/*global object that will dynamically update with data relevent only to the activeVideo. 
 Configured thus to allow Omniture and possibly other future products requiring data of the active video. */ 

var activeData = {
  "activeCategoryData": {
    "": ""
  },
  "activeVideoData": {"category": "","contentPath": "", "id": "","relatedItems": "","tip": "","title": "","subtitle": "",
    "videoPath": "",
    "type": "",
    "thumbnailPath": "",
    "placeholderPath": "",
    "omnitureId": "",
    "date": "",
    "startDate": "",
    "endDate": "",
    "isModal": "",
    "duration": 0,
    "height": "","width": "","fileName": "","autoPlay": "","remainingTime": 0,"lastAction": "","action": "","actionTime": 0
  }
}

/* Used to convert time in the colon/digital format to actual seconds. Used currently only for omniture tracking. 
 Passing a string in the format '10:12' or '10:12:14' to the function will return the equivalent seconds */
function convertToSeconds(time) {
  var t = time.toString()
  var hours = 0;
  var minutes = 0;
  var seconds = 0;
  var tLen = t.split(":").length;
  var timeInSeconds;
  $.each(t.split(":"), function (i) {
    if (tLen == 2) {
      if (i == 0) {
        minutes = parseFloat(this * 60);
      }
      else if (i == 1) {
        seconds = parseFloat(this);
      }
    }
    else if (tLen == 3) {
      if (i == 0) {
        hours = parseFloat(this * 60 * 60);
      }
      else if (i == 1) {
        minutes = parseFloat(this * 60);
      }
      else if (i == 2) {
        seconds = parseFloat(this);
      }
    }
    timeInSeconds = parseFloat((hours) + (minutes) + (seconds));
  })
  return timeInSeconds;
}

/*Sends information to Omniture */
function sendOmnitureDataToJS(action, time) {
  activeData.activeVideoData.lastAction = lastAction;
  activeData.activeVideoData.action = action;
  activeData.activeVideoData.actionTime = convertToSeconds(time);
  activeData.activeVideoData.remainingTime = ((activeData.activeVideoData.duration) - (activeData.activeVideoData.actionTime));
 log.info("sendOmnitureDataToJS", "JS: sendOmnitureDataToJS function called and with action: "+action, 5);
  var remainingTime = ((activeData.activeVideoData.duration) - (activeData.activeVideoData.actionTime));
  if (lastAction != action) {
    var offset = activeData.activeVideoData.actionTime;
	log.info("sendOmnitureDataToJS", "JS: offset: "+offset, 5);
    switch (action) {
    case 'PLAY':
      if (offset == 0) {
        s.Media.open(activeData.activeVideoData.title, activeData.activeVideoData.duration, "default");
		s.pageName = "video|" + activeData.activeVideoData.title.replace(/ /g, "_").toLowerCase();
        s.t();
		pixel_conversion('2454');
      }
      s.Media.play(activeData.activeVideoData.title, offset);
      break;
    case 'STOP':
      if (offset != 0) {
        s.Media.stop(activeData.activeVideoData.title, offset);
        break;
      }
      break;
    }
  }
  lastAction = action;
  activeData.activeVideoData.lastAction = action;
}


/*Central function that receives the path to a valid FLV and proceeds to play the video*/
function sendPathToFlash(_pathToVideo) {
  if (!DetectFlashVer(9, 0, 0)) {
    $("div.bmg_videodemo_l:first").find("object").remove();
    $("div.bmg_videodemo_l:first").find("embed").remove();
    $("div.bmg_videodemo_l:first").prepend("<div class='noFlashCont' style='width: 446px; height: 357px'><span style='margin-top:170px; float: left; margin-left: 15px;'>To view the videos, please download the <a href='http://get.adobe.com/flashplayer/' target='_blank'>Flash Player.</a> </span></div>");
    return;
  }
	try {
		if (navigator.appName == "Netscape") {
			document.Videos.loadVideo(activeData.activeVideoData.videoPath);
			/*document.Videos.loadVideo(activeData.activeVideoData.videoPath,activeData.activeVideoData.id,activeData.activeVideoData.title,activeData.activeVideoData.duration); */
		} else {
			document.getElementById("Videos").loadVideo(activeData.activeVideoData.videoPath);
			/*document.getElementById("Videos").loadVideo(activeData.activeVideoData.videoPath,activeData.activeVideoData.id,activeData.activeVideoData.title,activeData.activeVideoData.duration); */
	    }
	} catch (e) {
		log.error("sendPathToFlash", "Error in sendPathToFlash: " + e.message);
	}
}


/* Set the video status. This is used by Flash */
function setVideoStatus(_isPlaying) {
  this.isPlaying = _isPlaying;
  document.title = pageTitle + flashTitle;
}

var videoStopped = false;
/* Stop the video  */
function stopVideo() {
  try {
    if (navigator.appName == "Netscape") {
      videoTime = document.Videos.stopVideoFromJS();
    } else {
      videoTime = document.getElementById("Videos").stopVideoFromJS();
    }
    videoStopped = true;
     sendOmnitureDataToJS("STOP", videoTime);
  } catch (e) {
    log.error("stopVideo", "Error in stopVideo: " + e.message);
  }
}

/* Creates a popup window that will play the passed .swf video as well as update content on page, page title etc.*/

function bigimage(vidPath, vidId, vidWidth, vidHeight, vidDuration, vidContentPath, vidTitle, vidCat, vidDate) {
	typeof newwin=='undefined'?'':newwin.close();
  str1 = "<object id='abcd' width=\"" + vidWidth + "\"";
  str1 += "\" height=\"" + vidHeight;
  str1 += "\"codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0\"classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"><param value=\"";
  str1 += vidPath + "\" name=\"movie\"/><param value=\"high\" name=\"quality\"/><embed width=\"";
  str1 += vidWidth + "\" height=\"";
  str1 += vidHeight + "\"pluginspace=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" quality=\"high\" src=\"";
  str1 += vidPath + "\"/></object>";
  vidWidth1 = parseInt(vidWidth) + (70);
  vidHeight1 = parseInt(vidHeight) + (190);
  sw = (screen.width - vidWidth) / 2;
  sh = (screen.height - vidHeight) / 2;
  newwin = window.open('about:blank', 'newwin', 'width=' + vidWidth1 + ',height=' + vidHeight1 + ',scrollbars=0,menubars=0,toolbars=0,location=0,directories=0,status=0,top=0,left=0,resizable=1');
  newwin.document.open();
  newwin.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n');
  newwin.document.write('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
  newwin.document.write('\n<html>\n<head>\n<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />\n');
  newwin.document.write('<meta http-equiv="Imagetoolbar" content="no" />\n');
  newwin.document.write('<title>' + vidTitle + '</title>\n');
  newwin.document.write('<link href="/qptcms/qCmsRepository/Global/largeBusiness/css/base.css" rel="stylesheet" type="text/css"><link href="/qptcms/qCmsRepository/Global/largeBusiness/css/desktop.css" rel="stylesheet" type="text/css"><link href="/qptcms/qCmsRepository/Global/largeBusiness/css/themes.css" rel="stylesheet" type="text/css"><link href="/qptcms/qCmsRepository/Global/largeBusiness/css/layouts.css" rel="stylesheet" type="text/css"><link href="/qptcms/qCmsRepository/Global/largeBusiness/css/bmg.css" rel="stylesheet" type="text/css"><link href="/qptcms/qCmsRepository/Global/largeBusiness/css/bmg_menu.css" rel="stylesheet" type="text/css"><link href="/qptcms/qCmsRepository/Global/largeBusiness/css/bmg_features.css" rel="stylesheet" type="text/css"><link href="/qptcms/qCmsRepository/Global/qPortal/css/bmg_modal_window.css" rel="stylesheet" type="text/css" /><link href="/qptcms/qCmsRepository/Global/largeBusiness/css/thickbox.css" rel="stylesheet" type="text/css"><link href="/qptcms/qCmsRepository/Global/largeBusiness/css/bmg_video_news.css" rel="stylesheet" type="text/css">');
  newwin.document.write('</head>\n');
  newwin.document.write('<body style="margin:0;padding:0" scroll="auto">\n');
  newwin.document.write('<div class="bmg_layout_modal_675" id="interactiveVideo"><table width="100%" border="0" cellpadding="0" cellspacing="0" class="bmg_lgr_modal"><tr class="top64"><td valign="top"><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td class="modal_tl">&nbsp;</td><td class="modal_tc"><div class="lgr_modal_title" style="height:45px;"><div class="bmg_video_info"><h4><span class="catg">' + vidCat + '</span><br /><span>' + vidTitle + '</span><br /><span class="date">' + formatDate(vidDate) + '</span><span class="duration">' + vidDuration + '</span></h4><div class="bmgCL_clear"></div></div></div></td><td class="modal_tr">&nbsp;</td></tr></table></td></tr><tr class="middle"><td><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td class="modal_ml">&nbsp;</td><td class="modal_mc_hauto" colspan="" valign="top"><div class="modal_mc_container"><div class="bmg_video_content"><p>' + vidContentPath + '</p><div>' + str1 + ' </div><div class="modalBtn"><a class="bmg_button_gen_wt" href="#"><span onclick="self.close()">Exit</span></a></div></div></div></td><td class="modal_mr">&nbsp;</td></tr></table></tr><tr class="bottom"><td><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td class="modal_bl">&nbsp;</td><td class="modal_bc">&nbsp;</td><td class="modal_br">&nbsp;</td></tr></table></td></tr></table></div>');
  newwin.document.write('<script>  	</script>');
  newwin.document.write('\n</body></html>');
  newwin.document.close();
  newwin.focus();
}




/*Build the tooltip HTML and store in a var ready to embed */

var strVar = "";
	strVar += "<div class='vd_toolTip vd_left' style='font-size: 75%;'>";
	strVar += "    <div class='vd_toolTip_container'>";
	strVar += "        <div class='vd_toolTip_title'>";
	strVar += "            <h3 class='catg'><\/h3>";
	strVar += "            <h3 class='title'><\/h3>";
	strVar += "            <h3 class='date'><\/h3>";
	strVar += "            <h3 class='duration'><\/h3>";
	strVar += "            <div class='bmgCL_clear'>";
	strVar += "            <\/div>";
	strVar += "        <\/div>";
	strVar += "        <div class='vd_toolTip_content'>";
	strVar += "            <div class='vd_toolTip_head'>";
	strVar += "                <p>";
	strVar += "                    Description:";
	strVar += "                <\/p>";
	strVar += "            <\/div>";
	strVar += "            <div class=vd_toolTip_desc>";
	strVar += "                <p>";
	strVar += "                <\/p>";
	strVar += "            <\/div>";
	strVar += "        <\/div>";
	strVar += "    <\/div>";
	strVar += "<\/div>";

/*returns a truncated block of the passed string. Looks for a defined ellipsis.  
the global var 'minLength' can be defined to get the minimum length desired before the truncation */
function truncateTitle(str,num) {
	var arrWords = "";
	var wordLen=0;
	if ((str.length) < ((typeof num=='undefined'?minLength:num) - (ellipsisMark.length))) {
		arrWords = str;
	}
	else {
		$.each(str.split(" "), function(i, n){
			wordLen += n.length + 1;
			if ((wordLen) > ((typeof num=='undefined'?minLength:num)- (ellipsisMark.length))) {
				arrWords += ellipsisMark;
				return false;
			}
			i!=0?arrWords += " " + n:arrWords +=n;
		})
	}
	return arrWords;
}


/*Returns the passed shortened month date in a 'full_month day, year' format */ 
function formatDate(str) {
      var dateFormat = str.split(' ');
      var fullMonth = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
      var shortMonth = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
      $.each(shortMonth, function (i) {
        if (dateFormat[1] == this) {
          dateFormat[1] = fullMonth[i];
          return false;
        } 
      });
      
	 if(dateFormat[1].indexOf(",")!=-1) 
	 {dateFormtat = dateFormat[0] + " " + dateFormat[1] + " " + dateFormat[2];}
	 else{ dateFormtat = dateFormat[1] + " " + dateFormat[0] + ", " + dateFormat[2];}
	  return dateFormtat; 
}

/*Updates Paging*/
function updatePaging(obj){
	$(obj).data("category_Data").abc = ($(obj).data("category_Data").clicksDown * thumbsPerSlide + 1) + " - " + (((($(obj).data("category_Data").clicksDown + 1) * thumbsPerSlide) >= ($(obj).data("category_Data").numberOfThumbs)) ? ($(obj).data("category_Data").numberOfThumbs) + " of " + ($(obj).data("category_Data").numberOfThumbs) : (($(obj).data("category_Data").clicksDown + 1) * thumbsPerSlide) + " of " + ($(obj).data("category_Data").numberOfThumbs));
    $(obj).data("category_Data").pagination.text($(obj).data("category_Data").abc);
}

/*Does desired actions when the scroll-up button is clicked
Configures the 'distance' to slide and the slide speed in the global vars */
function boundEventsUp(obj, bool){
	if (bool) {
        $(obj).data("category_Data").thisCategoryContainer.find("dl").animate({
            top: '+=' + defaultTemplateHt + 'px'
        }, slideSpeed, function(){
        });
    }
    if (($(obj).data("category_Data").clicksUp * thumbsPerSlide) + $(obj).data("category_Data").remainders == $(obj).data("category_Data").numberOfThumbs) {
		$(obj).data("category_Data").thisUpScroller.css({"display":"none", "width":"0px", "height":"0px"}).parent().addClass("scrollUp_disabled");
		return false;
    }
    else {
        $(obj).data("category_Data").thisUpScroller.css({"display":"block", "width":"35px", "height":"35px"}).parent().removeClass("scrollUp_disabled");
    }
    updatePaging(obj);
}

/*Does desired actions when the scroll-down button is clicked
Configures the 'distance' to slide and the slide speed in the global vars */
function boundEventsDown(obj, bool){
	if (bool) {
        $(obj).data("category_Data").thisCategoryContainer.find("dl").animate({
            top: '-=' + defaultTemplateHt + 'px'
        }, slideSpeed, function(){
        });
    }
    if (((((($(obj).data("category_Data").remainders)==0)?($(obj).data("category_Data").clicksDown)+1:($(obj).data("category_Data").clicksDown))) * thumbsPerSlide) + $(obj).data("category_Data").remainders == $(obj).data("category_Data").numberOfThumbs) {
        $(obj).data("category_Data").thisDownScroller.css({"display":"none", "width":"0px", "height":"0px"}).parent().addClass("scrollBtm_disabled");
		return false;
    }
    else {
        $(obj).data("category_Data").thisDownScroller.css({"display":"block", "width":"35px", "height":"35px"}).parent().removeClass("scrollBtm_disabled");
    }
    updatePaging(obj);
}

/*Binds the clicks to the up and down scrollers. */
function bindClick(obj,bool){
	$(obj).data("category_Data").thisUpScroller.bind("click", function(index, n){
		$(obj).data("category_Data").clicksUp = $(obj).data("category_Data").clicksUp >= 0 ? $(obj).data("category_Data").clicksUp + 1 : 0;
		$(obj).data("category_Data").clicksDown = $(obj).data("category_Data").clicksDown > 0 ? $(obj).data("category_Data").clicksDown - 1 : 0;
		boundEventsUp(obj, true);
		boundEventsDown(obj);
    })
	$(obj).data("category_Data").thisDownScroller.bind("click", function(index, n){
		$(obj).data("category_Data").clicksDown = $(obj).data("category_Data").clicksDown >= 0 ? $(obj).data("category_Data").clicksDown + 1 : 0;
		$(obj).data("category_Data").clicksUp = $(obj).data("category_Data").clicksUp > 0 ? $(obj).data("category_Data").clicksUp - 1 : 0;
		boundEventsDown(obj, true);
		boundEventsUp(obj);
	});
}

/*Updates data() to an element with active data. Also handles onload scroll-into-view/content change based on reading the URL */
function onLoadTrigs(b, str){
	activeCategoryName = $(b).data("category_Data").thisCategoryName;
	$(".bmg_videodemo_tabConatiner").data("activeData", {
        "activeCategoryLink": $(b),
        "activeCategory": $(b).data("category_Data").thisCategoryContainer
    })
    $(b).data("category_Data").thisCategoryContainerVideos.each(function(){
        if ($(this).data("thumbAnchor_Data").fileName.toLowerCase() == str) {
			$(".bmg_videodemo_tabConatiner").data("activeData").activeElem = $(this)
			$(".bmg_videodemo_tabConatiner").data("activeData").activeElemFilename = $(this).data("thumbAnchor_Data").fileName;
			$(".bmg_videodemo_tabConatiner").data("activeData").activeElemABC = $(this).parents("dd:first").data("dd_Data").ABC;
            for (i = 1; i <= $(".bmg_videodemo_tabConatiner").data("activeData").activeElemABC; i++) {
                setTimeout(function(){
                    $(".bmg_videodemo_tabConatiner").data("activeData").activeCategoryLink.data("category_Data").thisDownScroller.trigger("click");
                }, 2);
            }
        }
		else if ($(this).data("thumbAnchor_Data").id.toLowerCase() == str) {
			$(".bmg_videodemo_tabConatiner").data("activeData").activeElem = $(this);
			$(".bmg_videodemo_tabConatiner").data("activeData").activeElemFilename = $(this).data("thumbAnchor_Data").fileName;
			$(".bmg_videodemo_tabConatiner").data("activeData").activeElemABC = $(this).parents("dd:first").data("dd_Data").ABC;
            for (i = 1; i <= $(".bmg_videodemo_tabConatiner").data("activeData").activeElemABC; i++) {
                setTimeout(function(){
                    $(".bmg_videodemo_tabConatiner").data("activeData").activeCategoryLink.data("category_Data").thisDownScroller.trigger("click");
                }, 2);
            }
		}
    })
	$(".bmg_videodemo_tabConatiner").data("activeData").activeCategoryLink.trigger("click");
	/*Need to check for All Videos */
	try {
		$(".bmg_videodemo_tabConatiner").data("activeData").activeElem.trigger("setCSSAndContent");
	}
	catch(e){
	}
	return;
}

/*Looks into categories (first as it will be faster)and if the video isnt found looks into the IDs or filenames. 
If there is nothing found then defaults to the globally set default active Video */ 
function returnActiveVideoId(str){
    $(".bmg_videodemo_tabCont").find("a").each(function(a, b){
        /*look for category first..faster */
        var abc = $(b).data("category_Data");
        $(abc).each(function(i, n){
            if ((n.thisCategoryName1).toLowerCase() == str) {
                onLoadTrigs(b, str);
                return false;
            }
            else {
				$.each($(b).data("category_Data").ids, function(i, obj){
                    if (str.toLowerCase() == obj.toLowerCase()) {
                        onLoadTrigs(b, str.toLowerCase());
                        return false;
                    }
                })
				$.each($(b).data("category_Data").fileNames, function(i, obj){
                    if (str.toLowerCase() == obj.toLowerCase()) {
                        onLoadTrigs(b, str.toLowerCase());
                        return false;
                    }
                })
            }
        })
    })
}

/*Utility function that hyphenates a passed string. Converts spaces inside of the string to hyphens. Used all around */ 
function hyphenate(str,makeLowerCase){
	return $.trim(typeof makeLowerCase!=undefined?str.toString().toLowerCase():str.toString()).replace(/ /gi, '-');
}

/*read the URL (includes hash) and gets the video string if avialable. Possible options include #category-name or #video-id or #video-filename or filename.html */
function storeObjFromActiveVideoId(){
    if (document.location.hash == '') {
		returnActiveVideoId(hyphenate(activeCategoryName,true));
		var docHTML = document.URL.slice(document.URL.lastIndexOf("/")+1);
		docHTML = docHTML.slice(0,docHTML.lastIndexOf(".")); 
		returnActiveVideoId(docHTML,true);
	}
    else {
        returnActiveVideoId(document.location.hash.replace("#", ""));
    }
}

/*Returns a loaded <li> tag that is relatively XSS safe as the manipulation is done at a string/text level */
function createXSSdTabs(d, e){
    var li = $('<li />', {
        'class': ''
    });
    var sp = $('<span />', {
        text: typeof e == 'undefined' ? ' ' + d.name : e,
        'class': 'vidTabs'
    });
    var al = $('<a />', {
        'class': (typeof e == "undefined"? "links": "lastTab"),
        'href': typeof e == 'undefined' ? '#' + hyphenate(d.name,true) : '#' + hyphenate(e,true)
    });
    al.append(sp);
    li.append(al);
    return li
}

/*Returns a loaded <li> tag that is targeted for older versions of jQuery. */
function createXSSdTabs1_2(d, e){
	var li = $('<li> <a class="links" href="'+((e == undefined)? ("#" + hyphenate(d.name,true)) : ("#" + hyphenate(e,true)))+'"><span>'+((e == undefined)? (" " + d.name) : e)+' </span> </a> </li>');
    return li
}

/*Returns a string with the HTML and content that builds the scrolling section inluding the scrollers and pagination.
The total number generated will depend on the number of categories */ 
function createXSSdThumbCont(a, b){
    var concatCat = typeof b != 'string' ?hyphenate(b.string,true) : hyphenate(b,true);
    var vidThumbStr = "";
    vidThumbStr += '<div class="bmg_videodemo_r ' + a + ' tooltip_block_container ' + concatCat + '" style="display:none;">';
    vidThumbStr += ' <div class="scroll_btn scroll_btnTop carArrowTop">';
    vidThumbStr += '<a class="hiddenDisp" href="javascript:;"></a>';
    vidThumbStr += '</div>';
    vidThumbStr += ' <div class="bmg_video_paging"></div>';
    vidThumbStr += ' <div class="bmgCL_clear"></div>';
    vidThumbStr += '<div class="scrollable_area" style="HEIGHT: ' + ((typeof b != "string") ? defaultTemplateHt : altTemplateHt) + 'px;position: relative"">';
    typeof b != 'string' ? vidThumbStr += '<dl class="carCol one" style="DISPLAY: block; position: relative">' : vidThumbStr += '<dl class="carCol two" style="DISPLAY: block; position: relative">';
    vidThumbStr += '</dl>';
    vidThumbStr += '</div>';
    vidThumbStr += '<div class="scroll_btn scrollBtm carArrowBott"><a class="hiddenDisp" href="javascript:;"></a></div>';
    vidThumbStr += '</div>';
    return vidThumbStr;
}


/*Returns a loaded dd with all information that will hold the eventual thumbnail for the videos */
function createXSSdThumbs(g, h){
    var dd = $('<dd />', {
        'class': ''
    });
    var div = $('<div />', {
        'text': truncateTitle(h.title.toString()),
        'class': 'bmg_videoTitle'
    });
    var div2 = $('<div />', {
        'class': 'bmg_videoIcon'
    });
	//alert(h.assetId);
    var anc = $('<a />', {
        'class': 'link',
        'href': h.videoPath + "#" + h.id
    }).data("thumbAnchor_Data", {
        "id": h.id,
        "category": h.category,
        "title": h.title,
		"title": h.title,
        "subtitle": h.subtitle,
        "videoPath": h.videoPath,
        "placeholderPath": h.placeholderPath,
        "thumbnailPath": h.thumbnailPath,
        "isModal": h.isModal,
		"isNewWin": typeof h.isNewWindow !='undefined'?h.isNewWindow:"false",		
        "contentPath": h.contentPath,
        "truncContentPath": h.contentPath,
        "date": formatDate(h.date),
        "startDate": h.startDate,
        "endDate": h.endDate,
        "duration": h.duration,
        "height": h.height,
        "width": h.width,
        "fileName": h.fileName,
		"assetId": typeof h.assetId !='undefined'?jQuery.trim(h.assetId):"undefined"
    });
    var imgs = $('<img />', {
        'src': h.thumbnailPath,
        'class': 'link'
    });
    dd.append(div);
    anc.append(imgs);
    div2.append(anc);
    dd.append(div2);
    return dd
}

/*same as above but targeted for older jquery versions */ 
function createXSSdThumbs1_2(g, h){
	var dd = $('<dd class=""><div class="bmg_videoTitle">'+truncateTitle(h.title.toString())+'</div><div class="bmg_videoIcon"><a class="link" href="'+h.videoPath + "#" + h.id+'"><img class="link" src="'+h.thumbnailPath+'"></a></div></dd>');
		dd.find("a").data("thumbAnchor_Data", {
	        "id": h.id,
	        "category": h.category,
	        "title": h.title,
	        "subtitle": h.subtitle,
	        "videoPath": h.videoPath,
	        "placeholderPath": h.placeholderPath,
	        "thumbnailPath": h.thumbnailPath,
	        "isModal": h.isModal,
	        "contentPath": h.contentPath,
	        "truncContentPath": h.contentPath,
	        "date": formatDate(h.date),
	        "startDate": h.startDate,
	        "endDate": h.endDate,
	        "duration": h.duration,
	        "height": h.height,
	        "width": h.width,
	        "fileName": h.fileName,
			"assetId": typeof h.assetId !='undefined'?jQuery.trim(h.assetId):"undefined"
	    });
	    return dd
}


/*creates useful category-specific data() that will be embedded into the category link element */
function createCategoryData(obj, xyz, allVid){
    var ddLen = $(xyz).find("dl dd").length;
    var thumbs = thumbsPerSlide;
    if (typeof allVid != 'undefined') {
		//alert("All Vid..in Create Category Data");
        ddLen = $(xyz).siblings().find("dl dd div.bmg_videoIcon a").length;
        thumbs = thumbsPerSlide * 2;
    }
    $(obj).data("category_Data", {
        "thisCategoryName": $.trim($(obj).text()),
        "thisCategoryName1": hyphenate($(obj).text(),true),
        "thisCategoryContainer": xyz,
		"thumb": thumbs,
        "thisCategoryContainerVideos": $(xyz).find("dl dd div.bmg_videoIcon a"),
        "thisCategoryContainerSiblings": xyz.siblings(".tooltip_block_container"),
        "thisCategoryContainerSiblingsVideos": $(xyz).siblings().find("dl dd div.bmg_videoIcon a"),
        "thisUpScroller": xyz.find("div.carArrowTop a"),
        "thisDownScroller": xyz.find("div.carArrowBott a"),
        "thisDefinitionLists": xyz.find("dl"),
        "thisContentBlock": xyz.siblings().find(".bmg_videodemo_detail_btm"),
        "thisPlaceholderBlock": xyz.siblings().find(".bmg_videodemo_detail_top"),
        "pagination": xyz.find("div.bmg_video_paging"),
        "clicksUp": parseInt(parseInt((ddLen / thumbs)).toFixed(0)),
        "clicksUpOrig": parseInt(parseInt((ddLen / thumbs)).toFixed(0)),
        "clicksDown": 0,
        "videos": [],
        "fileNames": [],
		//"thisListItem":$(obj).parents("li:first"),
		//"thisListItemSiblings":$(obj).parents("li:first").siblings(),
		"ids":[],
        "numberOfThumbs": ddLen,
        "numOfSlides1": parseInt(parseInt((ddLen / thumbs)).toFixed(0)) + 1,
        "numOfSlides2": parseInt((ddLen / thumbs).toFixed(0)),
        "remainders": (ddLen) % (thumbs)
    })
}

/*Returns the appropriate scrolling block from all the ones that are dynamically built and hidden by default.
Used primarily to show/hide the appropriate block when a category is clicked */
function returnCont(obj){
    var cont;
    $("div.videoContentContainer").find("div.bmg_videodemo_r").filter(function(){
        var abc = $(this).attr("class");
        var def = hyphenate($(obj).text(),true);
        if (abc.indexOf(def) != -1) {
            cont = $(this);
            return $(this);
        }
    })
    return cont
}

/*Builds the category tabs */
function bindTabLink(abc, obj){
	$(abc).bind("click", function(){
		if($(this).data("category_Data").thisCategoryName=="All Videos"){
			thumbsPerSlide = thumbsPerSlide*2;
			defaultTemplateHt = altTemplateHt;
			//alert($(abc).data("category_Data").thisDefinitionLists.children("dd").length);
			$(abc).data("category_Data").thisCategoryContainer.data("thumbAnchor_Data").firstElem =  $(abc).data("category_Data").thisDefinitionLists.children("dd:first").find("a").data("thumbAnchor_Data").id;//id of the first
			$(abc).data("category_Data").thisCategoryContainer.data("thumbAnchor_Data").firstElemDOM =  $(abc).data("category_Data").thisDefinitionLists.children("dd:first");//first dd
			$(abc).data("category_Data").thisCategoryContainer.data("thumbAnchor_Data").numberOfVideos = $(abc).data("category_Data").thisDefinitionLists.children("dd").length;//total videos
			$(abc).data("category_Data").thisDefinitionLists.children("dd").removeClass("selected");
			if (!isPlaying) {
				$(abc).data("category_Data").thisDefinitionLists.children("dd:first").addClass("selected");
				$(abc).data("category_Data").thisCategoryContainer.data("thumbAnchor_Data").firstElemDOM.find("a").trigger("setCSSAndContent");
			}
		}
		else{
			thumbsPerSlide = 5;
			defaultTemplateHt = "420";
		}
        if (!isPlaying) {
			activeVideoId = $(abc).data("category_Data").thisCategoryContainer.data("thumbAnchor_Data").firstElem;
			//alert($(this).hasClass("lastTab"))
			if(!$(this).hasClass("lastTab")){
				$(abc).data("category_Data").thisCategoryContainer.data("thumbAnchor_Data").firstElemDOM.find("a").trigger("setCSSAndContent");
			}
			$($(this).data("category_Data").thisPlaceholderBlock).show();
			$(abc).data("category_Data").clicksDown = 0;
			$(abc).data("category_Data").clicksUp = $(abc).data("category_Data").clicksUpOrig;
			boundEventsUp(abc,false);
			boundEventsDown(abc,false);
			updatePaging($(abc));
			$(this).data("category_Data").thisDefinitionLists.css("top","0px");	
		}
		else{
			if (!$(this).parent("li").hasClass("selCateg")) {
				$(abc).data("category_Data").thisDefinitionLists.children("dd").removeClass("selected");
			}
			boundEventsUp(abc,false);
			boundEventsDown(abc,false);
			updatePaging($(abc));
		}
			$(this).parent("li").addClass("bmg_activeLink");
			$(this).parent("li").siblings().removeClass("bmg_activeLink");
			$(this).data("category_Data").thisCategoryContainerSiblings.fadeOut("fast");
			$(this).data("category_Data").thisCategoryContainer.fadeIn("slow");
	})
}

/*creates useful thumb-area-specific data() that is embedded into each scrolling block */ 
function createThumbCategoryData(a, b){
    var concatActiveCat = hyphenate(activeCategoryName,true);
    abcde = $("div.videoContentContainer").find("div.bmg_videodemo_r").eq(a);
    fghij = $("div.videoContentContainer").find("div.bmg_videodemo_l").eq(a);
    pagination = abcde.find("div.bmg_video_paging");
    upScroller = abcde.find("div.carArrowTop a");
    downScroller = abcde.find("div.carArrowBott a");
    abcde.hasClass(concatActiveCat) ? abcde.fadeIn("slow") : abcde.fadeOut("fast");
    abcde.data("thumbAnchor_Data", {
        "selectedVideo": activeVideoId,
        "thisIndex": a,
        "usesTemplate": "",
        "isSelectedCategory": abcde.hasClass(concatActiveCat)
    })
}


/*creates useful thumb-specific data() information that is embedded into each thumb */
function createDdData(i, dd, obj){
	var abc = ((i) % thumbsPerSlide != 0 ? (i) / thumbsPerSlide.toFixed(0) : (i) / thumbsPerSlide);
    if ((i + 1) % thumbsPerSlide == 0) {
    }
    $(dd).data("dd_Data", {
        "index": i,
        "height": $("img", dd).height(),
        "width": $("img", dd).width(),
        "tooltipTitle": "",
        "tooltipDescription": "",
        "ABC": abc,
		"truncatedTitle":truncateTitle($(dd).find("a").data("thumbAnchor_Data").title,27)
    });
    $(obj).data("category_Data").videos.push($(dd).find("a").data("thumbAnchor_Data").id);
    $(obj).data("category_Data").fileNames.push($(dd).find("a").data("thumbAnchor_Data").fileName);
	$(obj).data("category_Data").ids.push($(dd).find("a").data("thumbAnchor_Data").id);
    if ("#" + $("a", dd).data("thumbAnchor_Data").fileName == document.location.hash) {
    }
}

function triggerClick($this,abcd){
	var obj = $("li.bmg_activeLink:first").find("a");
		obj.parent("li").siblings("li").removeClass("selCateg");

		obj.parent("li").addClass("selCateg");
		if(abcd.isModal=='true'){
		activeData.activeVideoData.videoPath = "demoPath";
		sendPathToFlash("demoPath");
		var vidPathExt = (abcd.videoPath).lastIndexOf(".");
		var vidPath1 = (abcd.videoPath).slice(vidPathExt + 1);
		if (vidPath1 == "exe" || vidPath1 == "mpg") {
			$(".bmg_videodemo_detail_top").show();
			window.open(abcd.videoPath,"_blank","directories=no,menubar=no,resizable=yes,toolbar=no,left=0,top=0,width=780,height=620",false);
			$(obj).data("category_Data").thisPlaceholderBlock.find("img").attr("src", $this.data("thumbAnchor_Data").placeholderPath);
		}
		else if(abcd.id=="3014" ||abcd.id=="1005" || abcd.id=="3017" ){
		//	if($.browser.webkit){
				//alert('asdadas');
				activeData.activeVideoData.videoPath = "demoPath";
				sendPathToFlash("demoPath");
				$(".bmg_videodemo_detail_top").show();
				if(abcd.id=="3017"){
					//bigimage(abcd.videoPath, abcd.id, abcd.width, abcd.height, abcd.duration, abcd.contentPath, abcd.title, abcd.category, abcd.date);
					window.open('/business/qCmsRepository/Global/largeBusiness/resources/embedVideos/loadExternal.vm','interactiveVid','resizable=1,left=0, top=0,location=0,toolbar=0,directories=0,menubar=0,status=0,scrollbars=0, width=820px,height=795px')
				}
				if(abcd.id=="3014"){
					window.open('/business/qCmsRepository/Global/largeBusiness/resources/embedVideos/loadExternal1.vm','interactiveVid','resizable=1,left=0, top=0,location=0,toolbar=0,directories=0,menubar=0,status=0,scrollbars=0, width=880px,height=795px')
				}
				$(obj).data("category_Data").thisPlaceholderBlock.find("img").attr("src", $this.data("thumbAnchor_Data").placeholderPath);
		}
		else {
			$(".bmg_videodemo_detail_top").show();
			bigimage(abcd.videoPath, abcd.id, abcd.width, abcd.height, abcd.duration, abcd.contentPath, abcd.title, abcd.category, abcd.date);
		}
	}
	else {
		activeData.activeVideoData.videoPath = $this.attr("href");
		$(".bmg_videodemo_detail_top").hide();
		sendPathToFlash();
	}
	activeVideoId = $this.data("thumbAnchor_Data").id;
	document.location.hash= activeVideoId;
	$this.trigger("setCSSAndContent");
	//trigger the metrics AJAX call
	storeMetrics(abcd.assetId);
	return false;
}

function storeMetrics(assetId){	
	jQuery.ajax({
		type: "GET",
		url: assetMetricsPath,
		data: "assetId="+assetId+"&pageURL="+location.href, 
		success: function(data){
			log.info("storeMetrics","JS: Passed Asset Id: "+assetId+" to the metrics path: "+assetMetricsPath,5);
		},
		error: function(){
			log.error("JS: Could NOT pass Asset Id: "+assetId+" to the metrics path: "+assetMetricsPath);
		},
		complete: function(XMLHttpRequest, textStatus){
				
		}
    })
}

function bindThumbClick(obj,xyz){
	$(xyz).find("dl dd").each(function(i, o){
            createDdData(i, o, obj);
			$("div.bmg_videodemo_tabConatiner").data("ABCDEFG").allVid.push($(o).clone(true));
			$("a", this).bind("setCSSAndContent", function(index, ob){
				//alert($(o).siblings().length);
				$(obj).data("category_Data").thisPlaceholderBlock.find("a.playMovie").data("thumbAnchor_Data",$(this).data("thumbAnchor_Data"));
				$(obj).data("category_Data").thisPlaceholderBlock.find("a.playMovie").data($(this).data());
				$(o).addClass("selected").siblings().removeClass("selected");
				var $this = $(this);
				activeData.activeVideoData.videoPath = $this.data("thumbAnchor_Data").videoPath;
				activeData.activeVideoData.id = $this.data("thumbAnchor_Data").id;
				activeData.activeVideoData.title = $this.data("thumbAnchor_Data").title;
				activeData.activeVideoData.duration = convertToSeconds($this.data("thumbAnchor_Data").duration);
				$(obj).data("category_Data").thisContentBlock.find("h3.catg").text($this.data("thumbAnchor_Data").category);
                $(obj).data("category_Data").thisContentBlock.find("h3.title").text($this.data("thumbAnchor_Data").title);
                $(obj).data("category_Data").thisContentBlock.find("h3.date").text($this.data("thumbAnchor_Data").date);
                $(obj).data("category_Data").thisContentBlock.find("p").text($this.data("thumbAnchor_Data").contentPath);
				$(obj).data("category_Data").thisPlaceholderBlock.find("img").attr("src", $this.data("thumbAnchor_Data").placeholderPath);
				$(obj).data("category_Data").thisPlaceholderBlock.find("a.playMovie").attr("href", $this.data("thumbAnchor_Data").videoPath +"#"+$this.data("thumbAnchor_Data").id);				
				activeVideoId = $(this).data("thumbAnchor_Data").id;
			})
			var aaa = $("a", this);
			var bbb = $(obj).data("category_Data").thisPlaceholderBlock.find("a.playMovie")
			/*Important - Need to merge both */
			$(bbb).bind("click", function(index, ob){
                var $this = $(this);
				var abcd = $this.data("thumbAnchor_Data");
				triggerClick($this,abcd);
				 return false;
            })
            $(aaa).bind("click", function(index, ob){
                var $this = $(this);
				var abcd = $this.data("thumbAnchor_Data");

				triggerClick($this,abcd);
				return false;
            })
        })
}

$(document).ready(function(){
   	 jQuery.parseJSON(JSONobj); /*for jquery versions greater than 1.4.1; */
    var jqVer = parseFloat(jQuery.fn.jquery);
    /*eval(JSONobj) //for jquery versions less than 1.4.1; */
	$("div.bmg_videodemo_tabConatiner").data("ABCDEFG", {
		"allVid":[]
	})
	$.each(JSONobj.videos.categories.entry, function(a, b){
		$("div.videoContentContainer").append(createXSSdThumbCont(a, b));
        createThumbCategoryData(a, b);
		$(this.categories).each(function(c, d){
            if (jqVer > 1.3) {
                $("div.bmg_videodemo_tabConatiner").find("ul").append(createXSSdTabs(d));
                abcde.data("thumbAnchor_Data").numberOfVideos = $(this.videos.video).length;
                activeVideoId = activeVideoId == '' ? $(this.videos.video)[0].id : activeVideoId;
                var dt = $('<dt />', {
                    'text': d.name,
                    'class': '',
                    'style': 'display: none'
                });
                abcde.find("dl").append(dt);
            }
            else {
				$("div.bmg_videodemo_tabConatiner").find("ul").append(createXSSdTabs1_2(d));
                abcde.data("thumbAnchor_Data").numberOfVideos = $(this.videos.video).length;
                activeVideoId = activeVideoId == '' ? $(this.videos.video)[0].id : activeVideoId;
                var dt = $('<dt />', {
                    'text': d.name,
                    'class': '',
                    'style': 'display: none'
                });
                abcde.find("dl").append(dt);
            }
            $(this.videos).each(function(e, f){
                $.each(this.video, function(g, h){
                    if (jqVer > 1.3) {
                        abcde.find("dl").append(createXSSdThumbs(g, h));
                        if (g == 0) {
                            abcde.data("thumbAnchor_Data").firstElem = this.id;
                            abcde.data("thumbAnchor_Data").firstElemDOM = abcde.find("dl dd").eq(0);
                        }
                    }
                    else {
						abcde.find("dl").append(createXSSdThumbs1_2(g, h));
                        if (g == 0) {
                            abcde.data("thumbAnchor_Data").firstElem = this.id;
                            abcde.data("thumbAnchor_Data").firstElemDOM = abcde.find("dl dd").eq(0);
                        }
                    }
                })
            })
        })
    });
    $("body").append(strVar);
    var toolTip = $("body").find(".vd_toolTip:last");
    var catLength = $(".bmg_videodemo_tabCont").find("ul li").length;
    $("a.links").each(function(ind, obj){
        var xyz = returnCont(obj);
        createCategoryData(this, xyz);
        updatePaging(obj);
        bindClick(obj);
        bindThumbClick(obj,xyz);
		bindTabLink(this, obj);
    })
		$("div.videoContentContainer").append(createXSSdThumbCont("1", 'All Videos'));
		$("div.videoContentContainer").append('<div class="bmgCL_clear"> <!-- --></div>');
		$("div.bmg_videodemo_tabCont").find("li:last").after(createXSSdTabs('', 'All Videos'));
		wxyz = $("div.bmg_videodemo_tabCont").find("li:last").find("a");
        xyz = returnCont(wxyz);		
		//Clone all the elems from the previous tabs, get the truncated title from the elem, update the elem text with this and push into All Videos. Events/data carries forward.
		$(".bmg_videodemo_r").not(".all-videos").each(function(){
			$(this).find("dl").children("dd").each(function(){
				var clonedElem = $(this).clone(true);
				$(clonedElem).find(".bmg_videoTitle").text($(this).data("dd_Data").truncatedTitle);
				clonedElem.appendTo($(".all-videos").find("dl"));
			})
		})

		$(".all-videos").find("dl").children("dd").each(function(a,b){
			$(this).find("a").bind("click", function(){
				$(b).addClass("selected");
				$(b).siblings().removeClass("selected");
			})
		})

		$("div.bmg_videodemo_tabCont").find("li:last").find("a").each(function(ind, obj){
			createCategoryData(wxyz, xyz, true);
			updatePaging(obj);
			bindClick(wxyz,false);
			createThumbCategoryData(catLength);
			bindTabLink(this,obj);
		})

	 storeObjFromActiveVideoId();
	$("a", $("dl.carCol dd")).hoverIntent(function(){
        toolTip.find(".vd_toolTip_title").find("h3.catg").text($(this).data("thumbAnchor_Data").category);
        toolTip.find(".vd_toolTip_title").find("h3.title").text($(this).data("thumbAnchor_Data").title);
        toolTip.find(".vd_toolTip_title").find("h3.date").text($(this).data("thumbAnchor_Data").date);
        toolTip.find(".vd_toolTip_title").find("h3.duration").text($(this).data("thumbAnchor_Data").duration);
        toolTip.find(".vd_toolTip_desc").text($(this).data("thumbAnchor_Data").contentPath);
        toolTip.show().css({
			"top": ($(this).offset().top - 67)+"px", 
            "left": ($(this).offset().left + 123)+"px" 
        });

		var newTooltipHeight = toolTip.height();
		var newTooltipWidth = toolTip.width();
		if ( document.documentElement && (document.documentElement.scrollTop)) {
			browserTopY = document.documentElement.scrollTop; 
		} else {
			browserTopY = document.body.scrollTop; 
		}

		if ( document.documentElement && (document.documentElement.scrollLeft)) {     
			browserLeftX = document.documentElement.scrollLeft; 
		} else {
			browserLeftX = document.body.scrollLeft; 
		}
		var thisOffset1 = $(this).offset(); 
		var thisPosition1 = $(this).position(); 
		var leftSpace = thisOffset1.left - browserLeftX;
		var rightSpace = $(window).width() - ((thisOffset1.left + $(this).width()) - browserLeftX);
		var topSpace = thisOffset1.top - browserTopY;
		var bottomSpace = $(window).height() - (thisOffset1.top - browserTopY);
		var isRight = (newTooltipWidth <= rightSpace);
		var isLeft = (newTooltipWidth <= leftSpace);
		var isTop = (newTooltipHeight <= topSpace);
		var isBottom = (newTooltipHeight <= bottomSpace);
		if(isRight && (newTooltipHeight <= $(window).height() - (toolTip.offset().top - browserTopY)) && (topSpace > 35)) {
			toolTip.addClass('vd_left');
			toolTip.removeClass('vd_bottom');
			toolTip.removeClass('vd_top');
			toolTip.removeClass('vd_right');
			toolTip.css({
		        left: (thisOffset1.left+$(this).width())
		    });
		}
		else if(isLeft && ((newTooltipHeight <= $(window).height() - (toolTip.offset().top - browserTopY))) && (topSpace > 35)) {
			toolTip.addClass('vd_right');
			toolTip.removeClass('vd_bottom');
			toolTip.removeClass('vd_top');
			toolTip.removeClass('vd_left');
			toolTip.css({
		        left: (thisOffset1.left)-(newTooltipWidth)
		    });
		}
		else if(isTop && (toolTip.offset().left - (newTooltipWidth/2) - ($(this).width()/2) - browserLeftX >= 0) && (rightSpace >= newTooltipWidth/2 - $(this).width()/2)){
			toolTip.addClass('vd_bottom');
			toolTip.removeClass('vd_left');
			toolTip.removeClass('vd_right');
			toolTip.removeClass('vd_top');
			toolTip.css({
		        left: (thisOffset1.left - ((newTooltipWidth/2) - ($(this).width()/2))),
				top: ((thisOffset1.top) - (newTooltipHeight+62))
		    });
			if (jQuery.browser.msie) {
					var ver = parseInt(jQuery.browser.version);							
					if (ver <= 7) {
						toolTip.css({
							left: (thisOffset1.left - ((newTooltipWidth / 2) - ($(this).width() / 2))),
							top: ((thisOffset1.top) - newTooltipHeight - 5)
						});
					}
			}
		}
		else if(isBottom && (toolTip.offset().left - (newTooltipWidth/2) - ($(this).width()/2) - browserLeftX >= 0) && (rightSpace >= newTooltipWidth/2 - $(this).width()/2)){
			toolTip.addClass('vd_top');
			toolTip.removeClass('vd_left');
			toolTip.removeClass('vd_right');
			toolTip.removeClass('vd_bottom');
			toolTip.css({
		        left: (thisOffset1.left - (newTooltipWidth/2) + ($(this).width()/2)),
				top: ((thisOffset1.top)+$(this).height())
		    });
		}
		else {
			toolTip.addClass('vd_bottom');
			toolTip.removeClass('vd_left');
			toolTip.removeClass('vd_right');
			toolTip.removeClass('vd_top');
			toolTip.css({
		        left: (thisOffset1.left - ((newTooltipWidth/2) - ($(this).width()/2))),
				top: ((thisOffset1.top) - (newTooltipHeight+62))
		    });
		}
    }, function(){
        toolTip.css({
            "top": "-2000px",
            "left": "-2000px"
        });
    })
	$("div.bmg_videodemo_tabConatiner").find("ul").find("li a").each(function(i,n){
		$(this).data("category_Data").thisCategoryContainerSiblings = $(this).data("category_Data").thisCategoryContainer.siblings(".tooltip_block_container");
	})
});
