This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
Overview
Download & View Ra_collection[1].txt as PDF for free.
if(i$.isFunction(_56)){ try{ return _56(arg); } catch(exc){ console.log("error executing function "+fn+" - "+exc); } } } return i$.promise.resolved(_55); },_stopEventPropagation:function(evt){ if(evt){ if(evt.stopPropagation){ evt.stopPropagation(); }else{ evt.cancelBubble=true; } } },_applyKeyAction:function(evt){ var _57=evt.target||evt.srcElement; var _58=_57; var _59=null; while(!_59){ _58=_58.parentNode; if(_58._contextMenu){ _59=_58; } } var _5a=_59._contextMenu; switch(evt.keyCode){ case 13: wptheme.contextMenu._stopEventPropagation(evt); var _5b=i$.byId(_5a.id); i$.removeClass((_5a.shadowNode)?_5a.shadowNode:_5b,wptheme.contextMenu.css.show); var _5c=wptheme.contextMenu._findFocusNode(_5b); window.setTimeout(function(){ ((_5c)?_5c:_59).focus(); window.setTimeout(function(){ wptheme.contextMenu._applyAction(evt); },0); },0); return false; case 9: case 27: var _5b=i$.byId(_5a.id); i$.removeClass((_5a.shadowNode)?_5a.shadowNode:_5b,wptheme.contextMenu.css.show); var _5c=wptheme.contextMenu._findFocusNode(_5b); ((_5c)?_5c:_59).focus(); break; case 40: wptheme.contextMenu._moveFocus(evt,_5a,_57,"next"); return false; case 38: wptheme.contextMenu._moveFocus(evt,_5a,_57,"previous"); return false; } return true; },_moveFocus:function(evt,_5d,_5e,_5f){ var _60=_5e.links[_5f];
if(_60&&(_60._menuitem.type=="Header"||_60._menuitem.type=="Separator")){ var _61=false; var _62=null; while(!_62&&!_61){ _60=_60.links[_5f]; if(!_60){ _61=true; }else{ if(_60._menuitem.type!="Header"&&_60._menuitem.type!="Separator"){ _62=_60; } } } _60=_62; } if(_60){ var _63=i$.byId(_5d.id)._currentSelected; if(_63){ _63.blur(); } i$.byId(_5d.id)._currentSelected=_60; _60.focus(); } if(evt.preventDefault){ evt.preventDefault(); } },_applyFocusAction:function(evt){ var _64=evt.target||evt.srcElement; var _65=_64; var _66=null; var _67=_64._menuitem; while(!_66){ _65=_65.parentNode; if(_65._contextMenu){ _66=_65; } if(!_67){ _64=_64.parentNode; _67=_64._menuitem; } } var _68=_66._contextMenu; var _69=i$.byId(_68.id)._currentSelected; if(_69!=_64){ if(_69){ _69.blur(); i$.byId(_68.id)._currentSelected=null; } if(_67.type!="Header"&&_67.type!="Separator"){ i$.byId(_68.id)._currentSelected=_64; _64.focus(); } } return false; },_applyAction:function(evt){ var _6a=evt.target||evt.srcElement; var _6b=_6a; var _6c=null; var _6d=_6a._menuitem;
while(!_6c){ _6b=_6b.parentNode; if(_6b._contextMenu){ _6c=_6b; } if(!_6d){ _6a=_6a.parentNode; _6d=_6a._menuitem; } } var _6e=_6c._contextMenu; _6e.activeAction=true; var p=wptheme.contextMenu._checkFunction(_6d,_6d.actionFn,_6d,_6d.actionUrl); if(p){ p.then(function(_6f){ if(_6f&&i$.isString(_6f)){ var _70=_6d.actionHttpMethod||"GET"; if(_70!="GET"){ var _71=i$.createDom("form"); _71.setAttribute("action",_6f); _70=_70.toLowerCase(); switch(_70){ case "get": _71.setAttribute("method","GET"); break; case "delete": case "put": var _72=i$.createDom("input",{"type":"hidden","name":"x-methodoverride","value":_70.toUpperCase()}); _71.appendChild(_72); case "post": _71.setAttribute("method","POST"); _71.setAttribute("enctype","multipart/form-data"); break; default: } i$.byId("wpthemeComplementaryContent").appendChild(_71); _71.submit(); }else{ window.location.href=_6f; } } }); } },_applySubmenu:function(evt){ var _73=evt.target||evt.srcElement; if(!_73._jsonData){ _73=_73.parentNode; } if(_73._jsonData){ _73.setAttribute("id",_73._jsonData.id+"_"+_73._menuitem.id); wptheme.contextMenu.initSubmenu(_73,_73._menuitem.id,_73._jsonData); } },_transformIntoAbsolutePosition:function(_74){ var _75=_74.childNodes,_76,i=0,_77=false; while(_76=_75[i++]){ if(i$.hasClass(_76,"wpthemeMenuRight")){ _77=true; break;
}else{ if(i$.hasClass(_76,"wpthemeMenuLeft")){ break; } } } var _78=i$.createDom("div"); _78.className=_74.className; _78.appendChild(_76); i$.byId("wpthemeComplementaryContent").appendChild(_78); _78._contextMenu=_74._contextMenu; _74._contextMenu.shadowNode=_78; _74._contextMenu._menuIsRight=_77; var _79=i$.createDom("span"); _78.appendChild(_79); i$.addClass(_79,"wpthemeMenuOverlay"); _74._contextMenu.overlayNode=_79; _74._contextMenu.menuNode=_76; wptheme.contextMenu._updateAbsolutePosition(_74); return _78; },_updateAbsolutePosition:function(_7a){ var _7b=_7a._contextMenu._menuIsRight; var _7c=_7a._contextMenu.menuNode; var _7d=_7a._contextMenu.overlayNode; var _7e=wptheme.contextMenu._findPos(_7a); var _7f=2; _7d.style.left=(_7e[0]-_7f)+"px"; _7d.style.top=(_7e[1]-_7f)+"px"; _7d.style.width=(_7a.offsetWidth+(2*_7f))+"px"; _7d.style.height=(_7a.offsetHeight+(2*_7f))+"px"; var dir=document.getElementsByTagName("html")[0].getAttribute("dir"); if(dir!=null){ dir=dir.toLowerCase(); }else{ dir=""; } if(!(dir=="rtl")){ _7c.style.left=((_7b)?_7e[0]+_7a.offsetWidth:_7e[0])+"px"; }else{ _7c.style.left=((_7b)?_7e[0]+_7a.offsetWidth-_7a.scrollWidth:_7e[0])+"px"; } _7c.style.top=_7e[1]+"px"; },_adjustScreenPositionStart:function(){ return document.documentElement.scrollHeight; },_adjustScreenPositionEnd:function(_80){ var _81=document.documentElement.scrollHeight; if(_80!=_81){ document.documentElement.scrollTop=document.documentElement.scrollHeight; } },_findPos:function(obj){ var _82=curtop=0; if(obj.offsetParent){ do{ _82+=obj.offsetLeft; curtop+=obj.offsetTop; }while(obj=obj.offsetParent); return [_82,curtop]; } }}});
})(); (function(){ i$.merge({ "NO_ITEMS_0":"No hay elementos que visualizar.", "ERROR_LOADING_0":"Se ha producido un error al cargar el menú." },i$.fromPath("wptheme.contextMenu.nls",true)); })(); (function(){ if(!i$.isIE){ i$.addOnLoad(function(){ var _1=document.getElementsByTagName("SECTION"); for(var i=0;i<_1.length;i++){ if(i$.hasClass(_1[i],"a11yRegionTarget")){ var _2=_1[i]; var _3=null; var _4=_2.getElementsByTagName("SPAN"); for(var j=0;j<_4.length;j++){ if(i$.hasClass(_4[j],"a11yRegionLabel")){ _3=_4[j]; } } if(_3){ var _5=_3; var _6=_2; var _7=null; while((_6=_6.parentNode)!=null){ if(i$.hasClass(_6,"component-control")){ var m=_6&&(_6.className||"").match(/id-([\S]+)/); _7=m&&m[1]; break; } } if(_7){ var _8="wpRegionId"+_7; _5.setAttribute("id",_8); _2.setAttribute("aria-labelledby",_8); } } } } }); } })(); jQuery("document").ready(function() { if ( $( "#showContent" ).length ) { var objappVersion = navigator.appVersion; var objAgent = navigator.userAgent; var objbrowserName = navigator.appName; var objfullVersion = ''+parseFloat(navigator.appVersion); var objBrMajorVersion = parseInt(navigator.appVersion,10); var objOffsetName,objOffsetVersion,ix; // In Chrome if ((objOffsetVersion=objAgent.indexOf("Chrome"))!=-1) { objbrowserName = "Chrome"; objfullVersion = objAgent.substring(objOffsetVersion+7); document.getElementById("showContent").innerHTML="
"; } // In Microsoft internet explorer else if (!!(navigator.userAgent.match(/Trident/))|| (objOffsetVersion=objAgent.indexOf("MSIE"))!=-1) { objbrowserName = "Microsoft Internet Explorer"; objfullVersion = objAgent.substring(objOffsetVersion+5); if (document.all && document.querySelector && ! document.addEventListener) { document.getElementById("showContent").innerHTML="
"; } // In Safari else if ((objOffsetVersion=objAgent.indexOf("Safari"))!=-1) { objbrowserName = "Safari"; objfullVersion = objAgent.substring(objOffsetVersion+7); if ((objOffsetVersion=objAgent.indexOf("Version"))!=-1) objfullVersion = objAgent.substring(objOffsetVersion+8); } // For other browser "name/version" is at the end of userAgent else if ( (objOffsetName=objAgent.lastIndexOf(' ')+1) < (objOffsetVersion=objAgent.lastIndexOf('/')) ) { objbrowserName = objAgent.substring(objOffsetName,objOffsetVersion); objfullVersion = objAgent.substring(objOffsetVersion+1); if (objbrowserName.toLowerCase()==objbrowserName.toUpperCase()) { objbrowserName = navigator.appName; } } // trimming the fullVersion string at semicolon/space if present if ((ix=objfullVersion.indexOf(";"))!=-1) objfullVersion=objfullVersion.substring(0,ix); if ((ix=objfullVersion.indexOf(" "))!=-1) objfullVersion=objfullVersion.substring(0,ix); objBrMajorVersion = parseInt(''+objfullVersion,10);
"+$
"+$
if (isNaN(objBrMajorVersion)) { objfullVersion = ''+parseFloat(navigator.appVersion); objBrMajorVersion = parseInt(navigator.appVersion,10); } } }); /* Global variable declaration*/ var typeAheadTimeout; // to clear Timeout var currentValue; var ajaxParam = { // to hold paramaters to send to ajax url1 : '', //for 1st IDOL call url2 : '', // for second IDOL call url : '', paramData : {} }; var countEachBind = 0; var KEY = { UP : 38, DOWN : 40, TAB : 9, ENTER : 27 }; var comingFromPFinder = false; var urlCreationFilteredData; $(document).ready(function() { typeAheadInit(); }); function checkValidity(val) { if (typeof val !== "undefined" && val != null) { return true; } return false; } /* Initialise the typeahead and attach event handlers */ function typeAheadInit() { $("input[type='text']").each(function() { if ($(this).hasClass("reqTypeAhead")) { var typeAheadObjClass = $(this).data("predectivecontainer"); handleEvents(typeAheadObjClass, $(this)); });
}
} /* Event handler for keyboard and mouse events */ function handleEvents(typeAheadObjClass, reqTypeaheadBox) { // close typeahead on outside click - start - Richa $(document).click(function(e) { if (e.target.id != "search-input") { $('.predictive-results.search-predictive-results').hide();
} }); // close typeahead on outside click - end - Richa // call the typeahead function on input - insert or delete (reqTypeaheadBox).on("input", function() { if((reqTypeaheadBox.val() != undefined) && (reqTypeaheadBox.val() != (reqTypeaheadBox).attr("ghostText"))){ callTypeAhead(reqTypeaheadBox, typeAheadObjClass); } }); // call the typeahead function on input - IE8 if ($("body").hasClass("ie8")) { (reqTypeaheadBox).on("keydown", function(event) { if ((event.which != KEY.DOWN) && (event.which != KEY.UP) && (currentValue != (reqTypeaheadBox).attr("ghostText"))) { callTypeAhead(reqTypeaheadBox, typeAheadObjClass); } }); (reqTypeaheadBox).on("paste", function(event) { setTimeout(function() { callTypeAhead(reqTypeaheadBox, typeAheadObjClass) }, 1); }); jQuery(document).on("dragend",reqTypeaheadBox, function(event) { callTypeAhead(reqTypeaheadBox, typeAheadObjClass); }); } // handle arrow keys , enter, tab on typeahead box (reqTypeaheadBox).on("keydown", function(event) { if ($("." + typeAheadObjClass).length > 0) { if ((event.which != KEY.DOWN) && (event.which != KEY.UP)) { } else if ((event.which == KEY.DOWN)) { event.stopPropagation(); event.preventDefault(); $("." + typeAheadObjClass + " li a").first().focus(); $("." + typeAheadObjClass + " li a").removeClass("hover"); $("." + typeAheadObjClass + " li a").first().addClass("hover"); (reqTypeaheadBox).val($(document.activeElement).text()); // $(".typeAheadBox").val($(document.activeElement).text()); } /* else if(event.which == KEY.TAB){ var clearIcon = (reqTypeaheadBox).parents(".searchbg").find(".clear-search"); if($(clearIcon).length > 0 ){ $(clearIcon).focus(); } }*/ else if ((event.which == KEY.UP)) event.stopPropagation(); event.preventDefault(); $("." + typeAheadObjClass + " $("." + typeAheadObjClass + " $("." + typeAheadObjClass + "
{ li a").last().focus(); li a").removeClass("hover"); li a").last().addClass("hover");
// Click on the predictive results $(document).on("click", "." + typeAheadObjClass + " li a", function(event) { (reqTypeaheadBox).val($(this).text()); // If mobile device then check the type ahead behaviour if(isMobileDevice()){ //Since this is mobile & if the key is not true then we need to stop type ahead if(typeAheadClickBehaviorMobile && typeAheadClickBehaviorMobile != "true"){ $(this).parents(".predictive-results").remove(); (reqTypeaheadBox).focus(); //Also we are force returning the event here to stop the ajax call return; } } else { //Now this is not Mobile //Checking if the in Desktop/Tablet if the type ahead behaviour is disabled. if(typeAheadClickBehaviorDesktop && typeAheadClickBehaviorDesktop != "true"){ //Since it is set to something other than true, we are stoping this action $(this).parents(".predictive-results").remove();
(reqTypeaheadBox).focus(); //Also we are force returning the event here to stop the ajax call
function createQueryParams(val){ val = $.trim(val); if (val!='' || val!=null || val!=undefined) { var words = val.split(' '); lengthOfWordList = words.length; var text = ''; var fieldText = ''; //cn, hk, tw var cc = getCCLC('cc'); var lc = getCCLC('lc'); var addFieldTextData = false; //The "+AND+MATCH{pm_series_value,pm_name_value}:CLASS" was added for story 6921 as part of the RnD to improve the functionality of the type ahead. // This prevents the SKUs from Showing up in the type ahead. By restricting the class to "pm_series_value" & "pm_name_value". var addFieldText = 'MATCH{'+cc+',NoValue}:COUNTRY_CODE+AND+BIASVAL{pm_series_value,'+biasvalValue+'}:C LASS+AND+MATCH{pm_series_value,pm_name_value}:CLASS';
// if the user is on us-en/drivers/printer /laptop etc. var filterId = getFilterIdForDriversPage(); // if we have ID(s) defined in SSC if(filterId){ // add filter criteria addFieldText += "+AND+STRING{"+filterId+"}:NAVIGATIONPATH"; } if((cc=='tw'|| cc=='hk' || cc=='cn') && lc=='zh'){ addFieldTextData = true; } // adding false to override adding field text if(false && lengthOfWordList>1){ //more than one word fieldText = words[lengthOfWordList-1]; fieldText = 'WILD{*'+ fieldText +'*}:DRETitle'; if(addFieldTextData){ fieldText = addFieldText+'+AND+'+fieldText; } words[lengthOfWordList-1] = ''; text = words.join(' '); text = $.trim(text); ajaxParam.paramData['text'] = text; ajaxParam.paramData['fieldText'] = fieldText; console.log('FieldText --->'+ fieldText); console.log('Text --->'+ text); } else{ text = val+'*'; if(addFieldTextData){ //CR13588ALM fieldText = addFieldText; ajaxParam.paramData['fieldText'] = fieldText; } else{ // if we have a filter ID and haven't already added it if(filterId){ ajaxParam.url1 = addFieldTextConditionToURL(ajaxParam.url1, "+AND+STRING{"+filterId+"}:NAVIGATIONPATH", filterId); }else{ ajaxParam.paramData['fieldText'] = ''; if(ajaxParam.url1.indexOf('}:NAVIGATIONPATH') > -1){ ajaxParam.url1 = removeFieldTextCondition(ajaxParam.url1); } }
// This function makes the ajax call for typeahead function autocomplete(currentInput, typeAheadObjClass) { $("." + typeAheadObjClass + "").remove(); currentValue = (currentInput).val(); ajaxParam.paramData["cc"] = getCCLC("cc"); ajaxParam.paramData["lc"] = getCCLC("lc"); ajaxParam.paramData["searchContext"] = $( "#search-dropdown .search-category").val() != "" ? $( "#search-dropdown .search-category").val() : "All Support"; var modifiedCurrentValue = currentValue.replace("&","&"); //replace & with & for IDOL to understand //create query params including static params createQueryParams(currentValue); var requestJson = JSON.stringify(ajaxParam.paramData); var successHandlerParams = { 'currentValue':modifiedCurrentValue, 'currentInput':currentInput, 'typeAheadObjClass':typeAheadObjClass }; abortAjaxUtil(); // abort called to abort any previous typeahead ajax call //callAjaxUtil('typeahead',ajaxParam.url,'POST',getMatch,'JSON',requestJson,success HandlerParams,ajaxFailureHandler); //Updated Ajax call to Call IDOL directly: //Create the url here //ajaxParam.url = ajaxParam.url1.replace("QueryPlaceholder",modifiedCurrentValue); var idolUTF8Lc = $('#idolUTF8Lc').val(); //base URL from portal var url1 = ajaxParam.url1; ajaxParam.url = url1; if(ajaxParam.paramData['text']!=null){ ajaxParam.url += '&text='+ajaxParam.paramData['text']; } if(ajaxParam.paramData['fieldText']!=null && ajaxParam.paramData['fieldText']! =''){ ajaxParam.url += '&fieldtext='+ajaxParam.paramData['fieldText']; }
// Make the call here callAjaxUtil('typeahead',ajaxParam.url,'POST',recallIdol,'JSON',null,successHandler Params,ajaxFailureHandler); //callAjaxUtil('typeahead',ajaxParam.url,'GET',nonIdolTypeAhead,'JSON',null,success HandlerParams,ajaxFailureHandler); $(currentInput).parent(".hasTypeahead").find(".searching").show(); } /*This function takes the IDOL JSON response and makes sense out of it.*/ var RELEVANCE_DIFF = 10; //to be externalized var TYPEAHEAD_MAX_LIMIT = 8; //to be externalized /** * * * * * * */ var
This method is used when hp-core-service is utilized for type ahead in search. This method populates type ahead. @since R3.0 @author [email protected] nonIdolTypeAhead = function(data,successHandlerParams){ var extractedData = []; for (var i=0; i
} if(extractedData.length > 0){ createList(extractedData, extractedData.length, successHandlerParams.currentInput, successHandlerParams.currentValue, successHandlerParams.typeAheadObjClass); } } var recallIdol = function(data,successHandlerParams){ var totalResults; var responseDataJSON = data.autnresponse.responsedata.$; if(typeof(responseDataJSON)=='object'){ responseDataJSON = responseDataJSON.join(); } responseDataJSON = $.parseJSON(responseDataJSON); /* responseDataJSON = data; */ if(!(responseDataJSON.autnresponse.responsedata["autn:numhits"] == undefined)){ // if IDOL response is not error totalResults = responseDataJSON.autnresponse.responsedata["autn:numhits"].$; } else{ totalResults = 0; }
var modifiedCurrentValue = successHandlerParams.currentValue; var words = modifiedCurrentValue.split(' '); var lengthOfWordList = words.length; if (totalResults == 0 && lengthOfWordList>1) { // if there are no results //createQueryParams var fieldtext = ""; var addFieldText = 'MATCH{'+cc+',NoValue}:COUNTRY_CODE'; if((cc=='tw'|| cc=='hk' || cc=='cn') && lc=='zh'){ fieldtext = "&fieldtext="+addFieldText; } ajaxParam.url = ajaxParam.url1+'&text='+modifiedCurrentValue+fieldtext; //commenting to cancel the second call to IDOL //callAjaxUtil('typeahead',ajaxParam.url,'POST',callTypeAheadResultConstructor,'JSO N',null,successHandlerParams,ajaxFailureHandler); } else { callTypeAheadResultConstructor(data,successHandlerParams); } } var callTypeAheadResultConstructor = function(rawData, successHandlerParams){ new typeAheadResultConstructor(rawData,successHandlerParams).filter(); } var typeAheadResultConstructor = function(rawData, successHandlerParams) { var rawData = rawData; var relevantDataIntrim = []; var urlCreationTempData = []; //6523 - will store respoonse data to be used for url creation var relevantData = { "topic": { "suggestions": [] }, "product": { "suggestions": [] } }; var totalResults; var responseDataJSON = rawData.autnresponse.responsedata.$; if(typeof(responseDataJSON)=='object'){ responseDataJSON = responseDataJSON.join(); } responseDataJSON = $.parseJSON(responseDataJSON); /* responseDataJSON = rawData; */ if(!(responseDataJSON.autnresponse.responsedata["autn:numhits"] == undefined)){ // if IDOL response is not error totalResults = responseDataJSON.autnresponse.responsedata["autn:numhits"].$; } else{ totalResults = 0; }
var calcNodeDepth = function(clazzType, navPathValue){ switch(clazzType){ case "category_navigation": return 1; case "pm_series_value": return 2; case "pm_name_value": return 3; case "pm_number_value": return 4; default: return 5; } } this.filter = function() { //initialise array to store child node paths (array or arrays) us-6523 var childNodeParentArray=[]; if (totalResults == 0) { // if there are no results getMatch(relevantData,successHandlerParams); } else { rawData = responseDataJSON; //Initialize this function by creating an array of the relevant data from the raw data set by using the filtering logic by VKS var isMultipleResult = (rawData.autnresponse.responsedata["autn:hit"] ! = undefined && rawData.autnresponse.responsedata["autn:hit"].length == undefined) ? false : true; if (isMultipleResult) { //if there are multiple results, autn:hit would be an array otherwise a single object $.each(rawData.autnresponse.responsedata["autn:hit"], function(index, obj) { var tempData = {}; var tempDataforURL = {}; var elemNavPathValue = ((this["autn:content"].DOCUMENT.SHORTESTNAVIGATIONPATH.$).split('|').length) 2; //having a -2 as an empty string is created after the last '|' var elemClazzType = this["autn:content"].DOCUMENT.CLASS.$; var shortestNavPathLength = calcNodeDepth(elemClazzType, elemNavPathValue); //store child nodes if present only us-6523 //if(this["autn:content"].DOCUMENT.CHILDNODES.hasOwnProperty("$")) //{ // var childArray=this["autn:content"].DOCUMENT.CHILDNODES. $.split('|'); // childNodeParentArray.push(childArray); // }
} else { var tempData = {}; var tempDataforURL = {}; var elemNavPathValue = ((rawData.autnresponse.responsedata["autn:hit"] ["autn:content"].DOCUMENT.SHORTESTNAVIGATIONPATH.$).split('|').length) - 2; //having a -2 as an empty string is created after the last '|' var elemClazzType = rawData.autnresponse.responsedata["autn:hit"] ["autn:content"].DOCUMENT.CLASS.$; var shortestNavPathLength = calcNodeDepth(elemClazzType, elemNavPathValue)
} /*End*/ // Failure handler for ajax call function ajaxFailureHandler(){ $(".hasTypeahead .searching").hide(); } // Get the matched results for products and topics function getMatch(jsonData, paramObj) { // jsonData = jQuery.parseJSON(jsonData); var currentValue = paramObj.currentValue; var currentInput = paramObj.currentInput; var typeAheadObjClass = paramObj.typeAheadObjClass; $(".hasTypeahead .searching").hide(); var jsonProdLen = jsonData.product.suggestions.length; var jsonTopicLen = jsonData.topic.suggestions.length; var jsonTotalLength = jsonProdLen + jsonTopicLen; var jsonObj = new Array(); var j = 0; for (var i = 0; i < jsonProdLen; i++) { if ((currentValue != "")) { var tempData = {}; tempData["label"] = jsonData.product.suggestions[i].label; tempData["productId"] = jsonData.product.suggestions[i].productId; jsonObj[j] = tempData; j++; } } for (var i = 0; i < jsonTopicLen; i++) { if ((currentValue != "")) { var tempData = {}; tempData["label"] = jsonData.topic.suggestions[i].label; tempData["productId"] = (jsonData.topic.suggestions[i].productId); jsonObj[j] = tempData; j++; } } createList(jsonObj, jsonProdLen, currentInput, currentValue, typeAheadObjClass); } // This creates the DOM for the predictive results and append it function createList(jsonObj, jsonProdLen, currentInput, currentValue,typeAheadObjClass) { (currentInput).siblings("ul").remove(); /* * type head highlighting - creating array with each word in user query for * search box */ var userQuery = (currentInput).val(); var userQueryWord; var userQueryWordLen = 0;
if (userQuery != undefined && userQuery != "") { userQueryWord = userQuery.split(" "); } /* * type head highlighting - creating array with each word in user query for * search box - end */ var jsonLen = jsonObj.length; var typeaheadLeftHook = (currentInput).siblings(".typeaheadHook").val() + "px"; if($("html").attr("dir")=="ltr"){ var stringList = "
"; } else{ var stringList = "
"; } for (var i = 0; i < jsonLen; i++) { /* * type head highlighting - using array to highlight type ahead * suggestions */ for (var count = 0; count < userQueryWord.length; count++) { var toBeHighlighted = userQueryWord[count]; var suggestedStr = jsonObj[i].label; if (toBeHighlighted != "") { suggestedStr = highlightSuggestion(suggestedStr,toBeHighlighted); jsonObj[i].label = suggestedStr; } } /* * type head highlighting - using array to highlight type ahead * suggestions - end */ if (i == jsonProdLen) { stringList += "
} //This function calls the typeahead function after an interval of 100ms after user inputs function callTypeAhead(reqTypeaheadBox, typeAheadObjClass) { // this is to get the typeAheadLimit i.e. beyond this count no typeahead call, #arka var typeAheadLimit = reqTypeaheadBox.data("typeaheadlimit"); // Don't call IDOL for type ahead if the lenght of text is less than 2 or greater than the configured limit #arka if ((reqTypeaheadBox).val().length > 1 && (reqTypeaheadBox).val().length < typeAheadLimit) { clearTimeout(typeAheadTimeout); typeAheadTimeout = setTimeout(function() { autocomplete(reqTypeaheadBox, typeAheadObjClass) }, 100); // autocomplete(reqTypeaheadBox, typeAheadObjClass); } else { clearTimeout(typeAheadTimeout); $("." + typeAheadObjClass + "").remove(); $(".hasTypeahead .searching").hide(); } } /* created for typeahead keyword highlighting - Richa * this function creates and array from suggested string. Logic is to separate already highlighted * (keywords enfolded with <strong>) from other words. * to handle if user searches for s/t/r/o/n/g, need to remove <strong>highlighted from the suggestedStr */ function createSuggestedArr(suggestedStr) { var startTag = "<strong>"; var lastTag = ""; var remainingSuggestedStr = suggestedStr; var suggestedArr = [], arrCounter=0; var strongLastTagL = KEY.TAB; var strongFirstIndex = remainingSuggestedStr.indexOf(startTag); var strongLastIndex = remainingSuggestedStr.indexOf(lastTag); while(strongFirstIndex!=-1) { if (strongFirstIndex == 0){ var endTagLastIndex = strongLastIndex + strongLastTagL; suggestedArr[arrCounter] = remainingSuggestedStr.substring(0,endTagLastIndex); remainingSuggestedStr = remainingSuggestedStr.substring(endTagLastIndex); } else { suggestedArr[arrCounter] = remainingSuggestedStr.substring(0,strongFirstIndex); remainingSuggestedStr = remainingSuggestedStr.substring(strongFirstIndex);
} arrCounter++; strongFirstIndex = remainingSuggestedStr.indexOf(startTag); strongLastIndex = remainingSuggestedStr.indexOf(lastTag); } //strong doesnt occur if(remainingSuggestedStr!="") { suggestedArr[arrCounter] = remainingSuggestedStr; } return suggestedArr; } /* created for typeahead keyword highlighting - Richa * this function sends suggestion array to createHiglightedStr for adding strong tags * */ function highlightSuggestion(suggestedStrComplete, toBeHighlighted) { var suggestedArr = createSuggestedArr(suggestedStrComplete); var suggestedArrL = suggestedArr.length; var suggestedStr, finalSuggestedStr = ""; var noOfMatches; var regEx = new RegExp(toBeHighlighted, "gi"); for(var counterArr=0; counterArr<suggestedArrL; counterArr++) { suggestedStr = suggestedArr[counterArr]; noOfMatches = suggestedStr.match(regEx) != null ? suggestedStr.match(regEx).length : 0; /* * for the first matched string, add <strong> to the keyword based * on its "keyword" occurrence */ if (noOfMatches != 0) {
}
if (suggestedStr.indexOf("<strong>")==-1) { suggestedStr = createHiglightedStr(suggestedStr, toBeHighlighted); } /* * from the second match onwards, add <strong> to the keyword * based on its "keyword+" occurrence */ else { var index = suggestedStr.lastIndexOf(toBeHighlighted+''); if (index != -1) { firstPartStr = suggestedStr.substring(0, index); lastPartStr = suggestedStr.substring(index); suggestedStr = firstPartStr + createHiglightedStr(lastPartStr, toBeHighlighted); } }
} /*created for typeahead keyword highlighting - Richa * this function adds strong tag around matching text * */ function createHiglightedStr(strValue, toBeHighlighted) { var startTag = "<strong>"; var lastTag = ""; var index = strValue.toLowerCase().indexOf(toBeHighlighted.toLowerCase()); strValue = strValue.substring(0, index) + startTag + strValue.substring(index, index + toBeHighlighted.length) + lastTag + strValue.substring(index + toBeHighlighted.length); return strValue; } /* created for typeahead keyword highlighting - end - Richa */ function isHidePrediction(typeAheadObjClass, reqTypeaheadBox){ setTimeout(function() { if($("." + typeAheadObjClass + " li a").is(":focus") || $ (".clearQuestionText").is(":focus") ||(reqTypeaheadBox).is(":focus") ){ } else{ $("." + typeAheadObjClass).remove(); } }, 200);
}
/** * @returns */ function getFilterIdForDriversPage(){ var url = window.location.href; var id = ""; if(url.indexOf('drivers/printer') > 0){ id = printerId; }else if(url.indexOf('drivers/laptop') > 0){ id = laptopId; }else if(url.indexOf('drivers/desktop') > 0){ id = desktopId; } }
return id;
/** * This method will find the parameter named fieldText and * append additionalFieldText to it and modify the original * URL with the new overall fieldText * * @param url * @param additionalFieldText * @returns
*/ function addFieldTextConditionToURL(url, additionalFieldText, filterId){ var finalUrl = url; if(url.indexOf('}:NAVIGATIONPATH') == -1){ var indexOfFieldText = url.indexOf("fieldtext"); var urlPartOne = url.substr(0, indexOfFieldText); var urlPartTwo = url.substr(indexOfFieldText, url.length); var indexOfFieldTextEnd = urlPartTwo.indexOf('&'); var oldFieldText = urlPartTwo.substr(0, indexOfFieldTextEnd); var newFieldText = oldFieldText + additionalFieldText; var urlPartThree = urlPartTwo.substr(indexOfFieldTextEnd, urlPartTwo.length); finalUrl = urlPartOne + newFieldText + urlPartThree; // URL already has this condition }else{ // the URL has this condition with some other ID if(url.indexOf(filterId) == -1){ var var i = var
fieldTextParamString = '+AND+STRING{'; i = url.indexOf(fieldTextParamString); i + fieldTextParamString.length; j = url.indexOf('}:NAVIGATIONPATH');
/** * Remove fieldText param of navigation * path. For any search other than * SWD Type Ahead * @param url * @returns */ function removeFieldTextCondition(url){ var fieldTextParamString = '+AND+STRING{'; var fieldTextParamNavigation = '}:NAVIGATIONPATH'; var i = url.indexOf(fieldTextParamString); var j = url.indexOf(fieldTextParamNavigation); j = j + fieldTextParamNavigation.length; return url.slice(0, i) + url.slice(j, url.length); }/* Copyright (c) 2016, 2017, HP and/or its affiliates. All rights reserved. */ /******************************************************************************
* NAME * assetConversionIntegration.js * * DESCRIPTION * Has functions which can convert a potential Samsung product's * product or serial number into equivalent HP product number * or serial number, and vice-versa. * * *****************************************************************************/ /** * Converts HP product number to Samsung * and vice-versa using CAL * * @author [email protected] * */ function convertProductNumber(productNumberRequest, callback){ var responseData = {}; // set the request object var requestJSON = {}; requestJSON.productNumber = productNumberRequest.productNumber; requestJSON.captchaToken = productNumberRequest.captchaToken; requestJSON.cc=productNumberRequest.cc; requestJSON.lc=productNumberRequest.lc; var ssid = getSSIDForAssetConv('product'); var url = "/hp-pps-services/asset/conversion/productnumber?ssid=" + ssid; $.ajax({ type: 'POST', url : url, dataType:'json', data: JSON.stringify(requestJSON), type: "POST", beforeSend: function(xhr) { xhr.setRequestHeader('Content-Type', 'application/json'); $("#conversionGifSpinner").modal("show"); }, success : function(data) { // Set HPPN and EPN in final response responseData.hpProductNumber = data.hpProductNumber; responseData.equivalentProductNumber = data.equivalentProductNumber; // Check if it is an HP asset if(productNumberRequest.productNumber == data.hpProductNumber){ // input PN matches HPPN in response, HP Asset responseData.isHPAsset = true; }else{
}
// Not an HP asset responseData.isHPAsset = false;
// Check if the response has both HPPN and EPN if((data.hpProductNumber != null && data.hpProductNumber != '')
&&(data.equivalentProductNumber != null && data.equivalentProductNumber != '')){ // set match found as true responseData.isMatchFound = true; }else { // no match found responseData.isMatchFound = false;
} function getSSIDForAssetConv(type){ var secureTokenVal = $('#secureTokenField').val(); //retrieve string in which key is stored var tokenId; if(type == "product"){ tokenId = $('#samsungProductBtn').attr("token"); if(tokenId == null){ tokenId = $('#hpProductBtn').attr("token"); } } if(type == "serial"){ tokenId = $('#samsungSerialBtn').attr("token"); if(tokenId == null){ tokenId = $('#hpSerialBtn').attr("token"); } } var ssidValue = ""; if(secureTokenVal.indexOf(tokenId)!=-1){ //check if the token key is present in the string of tokens ssidValue = JSON.parse($("#secureFieldJson").val()); } return ssidValue[tokenId]; } /** * Converts HP serial number to Samsung * and vice-versa using an external service * * @author [email protected] *
*/ function convertSerialNumber(serialNumberRequest, callback){ var responseData = {}; // set the request object var requestJSON = {}; requestJSON.serialNumber = serialNumberRequest.serialNumber; requestJSON.captchaToken = serialNumberRequest.captchaResponse; requestJSON.cc=serialNumberRequest.cc; requestJSON.lc=serialNumberRequest.lc; var ssid = getSSIDForAssetConv('serial'); var url = "/hp-pps-services/asset/conversion/serialnumber?ssid=" + ssid; $.ajax({ type: 'POST', url : url, dataType:'json', data: JSON.stringify(requestJSON), type: "POST", beforeSend: function(xhr) { xhr.setRequestHeader('Content-Type', 'application/json'); $("#conversionGifSpinner").modal("show"); }, success : function(data) { // Set HPPN and EPN in final response responseData.hpSerialNumber = data.hpSerialNumber; responseData.equivalentSerialNumber = data.equivalentSerialNumber; responseData.status=data.status; responseData.statusMessage=data.statusMessage; if((data.equivalentSerialNumber != null && data.equivalentSerialNumber != '')){ // set match found as true responseData.isMatchFound = true; }else { // no match found responseData.isMatchFound = false;
"; if(!(typeof categories.category[0] !== 'undefined' && (categories.category[0]! == null))){ var hpeString = ""; var hpiString = ""; for(var key in categories.category) { var val= categories.category[key]; if(key=="hpiProducts" && val.length>0){ hpiString += otherProducts("",val,key,categorylistheading);/*sending a null string to other products as it is being appended on return*/ } else if(key=="hpeProducts"&& val.length>0){ hpeString += otherProducts("",val,key,categorylistheading); } } builtString += hpiString+hpeString + ' '
} if (!(jsonData.pfinder.worldwide.categories[0] == undefined)) { var globalCategories = jsonData.pfinder.worldwide.categories; var categoryString = "";
} function getResultCount(categories){ return categories.category.products.length; } pFinderResultClick = function(pOid){ //on click of certain pfinder results populate the value in a form and submit it instead of redirecting directly if($('#pFinderClickForm').length>0){ $('#pFinderClickPOid').attr('value',pOid); $('#pFinderClickForm').submit(); } } function isSWDPage(){ /*
$("#searchResultsWrapper").append(searchResultMarkupString); $(".search-result:not(:last)").after(""); } // External Link Image for Search Result Page // add external image symbol if needed $('.search-result a').each(function () { // "this" is the current element in the loop var link = this.href; // internal site regex var regex = new RegExp("([\w0-9._:/-]+hp.com(.*))"); if(link.indexOf('http') > -1 && !regex.test(link)){ $(this).append(' '); } }); } var promoIdsArr = []; function createSearchResultMarkup(searchResultsObj) { var builtString; var resultObj = searchResultsObj.searchResult; if((typeof(resultObj.searchId) == "undefined") && (typeof(resultObj.searchType) == "undefined")){ var Url= resultObj.searchURL; var splitUrl = Url.split("/"); var docID = splitUrl[splitUrl.length - 1]; builtString = "
"; promoIdsArr.push(resultObj.searchId); } return builtString; } /*Pagination - Richa */ function parsePaginationJson(pageJson) { var pageJson2 = pageJson; var current = pageJson.pagination.current; var total = pageJson.pagination.total; var first = pageJson.pagination.first; var last = pageJson.pagination.last; var totalCount = pageJson.totalCount;
var searchQueryForDisplay = pageJson.searchQueryForDisplay; var searchQuery = pageJson.searchQuery; var actualQuery = pageJson.actualQuery; var searchResultLink = pageJson.searchResultLink; var resultsFor = pageJson.foundResultFor; var facets = pageJson.facets; var productFacets = pageJson.ProductFacets; var osFacets = pageJson.OSFacets; var topicFacets = pageJson.TopicFacets; var promotionList = pageJson.promotionList; $("#promotionList").val(JSON.stringify(promotionList)); $("#searchResultsWrapper").html(""); var seoFriendlyName = pageJson.searchResults.seoFriendlyName; $("#seoFriendlyName").val(seoFriendlyName); paintPaginationSection(first,last,current,total); paintSearchResults(pageJson.searchResults); paintCountQuery(totalCount,searchQueryForDisplay,actualQuery,searchResultLink,searc hQuery,resultsFor); // do not reload facets if(facets==undefined || (facets!=undefined && facets!='empty')) paintFacets(productFacets,osFacets,topicFacets); $(".searchSectionWrapper").show(); // to bind - on click of clear and clear all bindClearFacets(); } function nonEnglishLocale(){ $(".englishResults").on("click tap",function (event){ searchlc = "en"; var count = $($(".resultsCount2")[0]).text(); $("#storeResultCount").val(count); englishResultsAjax(searchlc); }); $(".localeResults").on("click tap",function (event){ searchlc = getCCLC(lc); $("#storeResultCount").val(""); localResultsAjax(searchlc); }); } /*Locale based rendering */ function parsePaginationJsonEnglish(pageJson) { //$("#resultsInLc").addClass("hide"); if(pageJson.totalCount>0){ parsePaginationJson(pageJson); resultsEnglishJson(); } else{ }
noResultsEnglishJson();
} function parsePaginationJsonLocale(pageJson) {
parsePaginationJson(pageJson); //$("#resultsInLc").removeClass("hide"); $(".optionsResultsInLc").removeClass("hide"); $(".englishResults").removeClass("hide"); $(".localeResults").addClass("hide"); $(".resultsInEng").addClass("hide"); $(".englishLocale").addClass("hide"); $("#resultCurrentLocale").removeClass("hide"); $(".resultsInLocal").removeClass("locale-results"); $("#nonUSLocaleSecondView").html(""); $(".searchForNonENLocale").clone().appendTo("#nonUSLocaleSecondView"); $(".resultsColor").addClass("color-black"); $("#searchProdInfo").removeClass("hide"); nonEnglishLocale(); } function resultsEnglishJson() { $(".optionsResultsInLc").addClass("hide"); $(".englishResults").addClass("hide"); $(".localeResults").removeClass("hide"); $(".resultsInEng").removeClass("hide"); $(".englishLocale").removeClass("hide"); $("#resultCurrentLocale").addClass("hide"); $("#nonUSLocaleSecondView").html(""); $(".searchForNonENLocale").clone().appendTo("#nonUSLocaleSecondView"); $(".resultsInLocal").addClass("locale-results"); $(".resultsColor").removeClass("color-black"); $("#searchProdInfo").addClass("hide"); nonEnglishLocale(); } function noResultsEnglishJson() { $(".noEnglishResults").removeClass("hide"); $(".optionsResultsInLc").addClass("hide"); $(".englishResults").addClass("hide"); $("#nonUSLocaleSecondView").html(""); $(".searchForNonENLocale").clone().appendTo("#nonUSLocaleSecondView"); nonEnglishLocale(); } function paintCountQuery(totalCount,searchQueryForDisplay,actualQuery,searchResultLink,searc hQuery,resultsFor) { // populate 1.total count, 2,search query - user enters and 3.actual query search query if search query is misspelled. globalDataLayer.Search.setValue('Count',totalCount); $(window).trigger('SearchCount',{ SearchCount : totalCount }); $('.resultsCount1').html(totalCount); var totalCountLocal = $("#storeResultCount").val(); if(totalCountLocal!= undefined && totalCountLocal!=totalCount &&
totalCountLocal!=""){ $('.resultsCount2').html(totalCountLocal); } else{ $('.resultsCount2').html(totalCount); } $('.resultsCount3').html(totalCount); /* $('#search-input').val(searchQueryForDisplay); Removing this as the search query now is painted directly from searchparent.jsp */ $('#searchQuery').val(searchQuery); if($('#actualQuery')!=undefined) { $('#actualQuery').val(actualQuery); //$('#actualQuery').attr("href",searchResultLink); } if(resultsFor!='') { //$('#resultsCountSearch').html(resultsFor); //$('#resultsCountSearch_val').val(resultsFor); //Changes made for XSS Vulnerability $('#resultsCountSearch').html(""); var searchInput_Text = $('#search-input').val(); searchInput_Text = $('<span>', {text: searchInput_Text}); $('#resultsCountSearch').append(searchInput_Text); } } function paintPaginationSection(first,last,current,total) { // clear the existing pages and remove disabled class from button. $('.pagination-container ul.pagination-pages').html(''); enableDisablePageButton('enable'); // if only 1st page is displayed. if(first == 0) { $('.paginationWrapper').hide(); return; } else if( $('.paginationWrapper').css('display') == 'none' ) { $('.paginationWrapper').show(); } //paint the pages and add active class for(var count=first; count<=last; count++) { if(count == current) { $('.pagination-container ul.pagination-pages').append('
} if(current == total) { enableDisablePageButton('disable','more'); } $('ul.pagination-pages li').on('click',function() { if(!($(this).find('a').hasClass('active'))) { var current = $(this).find('a .pageCount').html(); var currentNum = parseInt(current); pagination(currentNum); } }); } function pagination(pageNum) { var ajaxParam = facetsPaginationParams(pageNum); var requestJson = JSON.stringify(ajaxParam.paramData); var pageURL = $('#paginationURL').val(); callAjaxUtil("pagination",pageURL,"POST",parsePaginationJson,"JSON", requestJson, null,null,null,true,handleLoadingResult,true,handleLoadingResult,false); } function pageButtonHandle(buttonVal) { var current = $('ul.pagination-pages li a.active .pageCount').html(); var currentNum = parseInt(current); if(buttonVal == "less") { pagination(currentNum-1); }else if(buttonVal == "more") { pagination(currentNum+1); } } //this function is called on beforesend and complete of ajax call for pagination function handleLoadingResult(showOrHide) { // showOrHide will be true for beforesend and false for complete if(showOrHide == true) { $('.hp-loading-results').show(); } else { $('.hp-loading-results').hide(); $(window).scrollTop(0); $("#searchResultsWrapper").find("a")[0].focus(); // This is to take the focus to the first result. } } function enableDisablePageButton(enableDisable,buttonName) { if(enableDisable == 'disable') { if(buttonName == 'less') { $('.pagination-button.paginationless').attr('disabled','disabled'); $('.pagination-button.pagination-less').css('backgroundcolor','#DDD'); } else { $('.pagination-button.paginationmore').attr('disabled','disabled'); $('.pagination-button.pagination-more').css('background-
color','#DDD'); } } else {
// enable less $('.pagination-button.pagination-less').removeAttr('disabled'); $('.pagination-button.pagination-less').css('background-
color','#FFF');
color','#FFF'); }
// enable more $('.pagination-button.pagination-more').removeAttr('disabled'); $('.pagination-button.pagination-more').css('background-
} /*Pagination - RIcha - end */ function handlePaginationRtl() { // RTL for pagination buttons - Richa if($('html').attr('dir') == 'rtl') { $('.pagination-button.pagination-less i').removeClass('fa fa-chevronleft').addClass('fa fa-chevron-right'); $('.pagination-button.pagination-more i').removeClass('fa fa-chevronright').addClass('fa fa-chevron-left'); } // RTL for pagination buttons - Richa - end } $(document).ready(function() { hpExpandableInit(); }); function hpExpandableInit() { $(document).on("click", ".hp-expand-colapse", function() { $(this).addClass("opened"); $(this).siblings(".hp-expandable-section").slideDown().addClass("opened"); }); $(document).on("click", ".hp-expand-colapse.opened", function() { $(this).removeClass("opened"); $(this).siblings(".hp-expandable-section").removeClass("opened").slideUp(); }); } /** * Protect window.console method calls, e.g. console is not defined on IE * unless dev tools are open, and IE doesn't define console.debug */ (function() { if (!window.console) { window.console = {}; } // union of Chrome, FF, IE, and Safari console methods var m = [ "log", "info", "warn", "error", "debug", "trace", "dir", "group",
"groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd", "dirxml", "assert", "count", "markTimeline", "timeStamp", "clear" ]; // define undefined methods as noops to prevent errors for (var i = 0; i < m.length; i++) { if (!window.console[m[i]]) { window.console[m[i]] = function() {}; } } })();// This plugin is based on the Bootstrap collapse component, with some extended functionality // This plugin looks for an element with a data-toggle="collapse" // The href attr of the toggle will determine which accordion to collapse/expand // If the toggle element also has a data-group attr, any accordion inside that #id will collapse, allowing only one to be visiblea at a time // Also you can pass in a data-scroll boolean on the toggle element, to determine wether the page will scrollTo the now visible accordion content // // This will control any expandable component, including Accordions, Sortable Table, and Instruction Panels Accordion = (function(){ var init = function(){ if($('[data-toggle="collapse"]').length){ addHandlers(); } }; var addHandlers = function(){ $('[data-toggle="collapse"]').on('tap click', checkState); $('[data-toggle="collapse"]').on('slideDown', slideDown); $('[data-toggle="collapse"]').on('slideUp', slideUp); $('.acc-ex-all').on('tap click', expandAll); $('.acc-coll-all').on('tap click', collapseAll); }; var checkState = function(e){ // This is the entry point. It checks the state of the accordion and handles its accordingly (lolz). e.preventDefault(); e.stopPropagation(); //Get the e.target handler var $toggle = $(this); var scroll = $toggle.data('scroll'); //IF IT IS UP, slide it down if(!$($toggle.attr('href')).hasClass('in')){ //IF IN GROUP, then we need to close all sibling panels in the group if($toggle.data('parent')){ var group = $toggle.data('parent'); $(group).find('[datatoggle="collapse"]').not($toggle).trigger('slideUp'); $toggle.trigger('slideDown', [scroll]); } else { $toggle.trigger('slideDown', [scroll]); } //IF DOWN, slide that up } else { $toggle.trigger('slideUp');
} }; var expandAll = function(e){ //This expands all panels in the group e.preventDefault(); var $toggle = $(this); var $group = $($toggle.data('group')); $group.find('[data-toggle="collapse"]').trigger('slideDown', [false]); }; var collapseAll = function(e){ //Collapses all panels in their group e.preventDefault(); var $toggle = $(this); var $group = $($toggle.data('group')); $group.find('[data-toggle="collapse"]').trigger('slideUp'); }; var slideDown = function(e, scroll){ //Slides down an individual panel var $toggle = $(this); var $panel = $ (this).addClass('toggled').closest('[class^="panel"]').addClass('open'); var accordionId = $toggle.attr('href'); var $accordion = $(accordionId); $toggle.attr("aria-expanded","true"); $accordion.slideDown(function(){ $(this).addClass('in'); if(scroll){ $('html, body').animate({scrollTop: $accordion.offset().top-200}, true); } if($(this).attr("id") == "os-selector"){ $(".os-heading").css("pointer-events",""); } }); }; var slideUp = function(e){ var $toggle = $(this); var $panel = $ (this).removeClass('toggled').closest('[class^="panel"]').removeClass('open'); var accordionId = $toggle.attr('href'); var $accordion = $(accordionId); $toggle.attr("aria-expanded","false"); $accordion.slideUp(function(){ $(this).removeClass('in'); if($(this).attr("id") == "os-selector"){ $(".os-heading").css("pointer-events",""); } }); }; return { init: init }; }());// This has been made obsolete by the addition of iCheck plugin // Saving code here for backup for now
}; var dClose = function(e){ e.stopPropagation(); $this = $(this); $this.removeClass('open'); }; var dOpen = function(e){ $this = $(this); $this.addClass('open'); };
return { init: init }; }());// This is placeholder code to demonstrate filter functionality // It basically adds a bunch of handlers to fire mock-AJAX calls and update the filter breadcrumbs // This has a dependency on iCheck Filters = (function(){ var filterTitles = {}; var init = function(){ var $inputs = $('.filter-options input[type="checkbox"]'); if($inputs.length){ addHandlers($inputs); } }; var addHandlers = function($inputs){ $inputs.on('change', applyFilter); $('[data-filter="clear"]').on('tap click', clearFilters); $('[data-filter="all"]').on('change', clearSiblingFilters); $('#filter-form').on('submit', submitFilters); $('.expandable').on('tap click', expand); $('[data-more]').on('tap click', expandLevel); $('#filter-trigger').on('tap click', showMobile); $('#filter-close').on('tap click', showMobile); if (window.addEventListener) { window.addEventListener('orientationchange', function(){ if (window.innerWidth > 800){
}()); //These elements are created from filters.js by clicking the input filters SCF = (function(){ var init = function(){ var $toggles; if ($('.applied-filters-item').length) { $toggles = $('.applied-filters-item').find('.filter-close'); addHandlers($toggles); } }; var initElem = function($el){ addHandlers($el.find('.filter-close')); }; var addHandlers = function($toggles){ $toggles.on('click', close); }; var close = function(e){ var $target = $(e.currentTarget); var $parent = $target.parent(); var $input; $input = $('#filter-form input.icheck\\[' + $target.attr('ref').split('[').pop().split(']').shift() + '\\]'); $input.prop('checked', false).change(); console.log($input.prop('checked')); if ($target.prop('tagName') === 'LI'){ $target.remove(); } else if ($parent.prop('tagName') === 'LI'){ $parent.remove(); } }; return { init: init, initElem: initElem }; })();Pagination = (function(){ var $pagContainer, $contentSelector, $controls, controlTriggers, maxResults, totalResults; var init = function(){ $pagContainer = $('.pagination-container'); if($pagContainer.length){ $contentSelector = $('.pagination-container li'); $controls = $('.pagination'); controlTriggers = '.pagination li a'; maxResults = 10; totalResults = $contentSelector.length; renderControls();
};
}
var renderControls = function(){ // // THIS MODULE IS STILL IN PROCESS // // }; return { init: init }; }());// This is to demonstrate functionality of the dependent select boxes // whenever a change is made in a parent select box, an ajax call needs to fire // to pull in the next set of options available // this is dependant on the fancy select plugin ajaxSelect = (function(){ // create a blank image object to reserver for our loader gif var loaderGif = new Image(); // var init = function(){ // grab all our instances var $ajaxSelects = $('[data-class="ajax-select"]'); var $fancySelects = $('.fancy-select'); if($ajaxSelects.length){ // add handlers addHandlers($ajaxSelects, $fancySelects); // this is dummy call fakeIt(); // set the image object's src loaderGif.src = ('_/images/i-pre-sm-hpe.gif'); $(loaderGif).addClass('select-loader'); // append a loader gid before each instance of the submit button or if no submit button // after all the select boxes $('.dependant-select').each(function(){ if($(this).find('input[type="submit"]').length){ $ (this).find('input[type="submit"]').before(loaderGif); } else { $(this).append($(loaderGif).clone()); } }); } }; // add our handlers var addHandlers = function($ajaxSelects, $fancySelects){ // change.fs is an event provided to us by fancy select $ajaxSelects.on('change.fs', callNextLevel); $fancySelects.on('open', open); };
// var open = function(e){ // } // This is a dummy call to hide all the results on one of the tabs in PDP, as well as hide all the // dependant select would otherwise not be visible/returned by ther server yet var fakeIt = function(){ $('.troubleshoot-results').hide(); // Hide all the selects except the first $('.dependant-select').each(function(){ $(this).find('.fancy-select.ajax-select').slice(1).hide(); }); // Make it so the first dropdown is expanded by default. omg this is so ugly why. much bad ux. $('.dependant-select.open').each(function(){ $(this).find('.fancy-select.ajaxselect').first().children().addClass('open'); }); }; // this fires after the change event on a fancy select box var callNextLevel = function(e){ // set up some variables for the AJAX call var $select = $(this); var $parent = $select.parent(); var $form = $(this).parents('form'); var url = $form.attr('action'); // show the loader while the AJAX call is made if( $select.parent().next('.fancy-select').length){ $select.parent().siblings('.select-loader').css({'display': 'block'}); } else { $select.parent().removeClass('last'); } // this timeout fakes the time it would take for an ajax to complete setTimeout(function(){ $.ajax({ type: "POST", url: url, data: $form.serialize(), // serializes the form's elements. success: function(data) { // DO SOME STUFF IN HERE TO BUILD OUT THE NEXT LEVEL's SELECT OPTIONS BASED ON DATA RETURNED FROM SERVER if( $select.parent().next('.fancy-select').length){ $select.parent().removeClass('last'); $select.parent().next('.fancyselect').show().addClass('last').children('select').focus(); $select.parent().siblings('.select-loader').hide(); } else { $select.parent().siblings('.select-loader').hide(); $('.troubleshoot-results').show(); } }, error: function(data){ if( $select.parent().next('.fancy-select').length){
$select.parent().next('.fancy-select').show(); $select.parent().removeClass('last'); $select.parent().next('.fancyselect').show().addClass('last'); $form.find('.select-loader').hide(); } else { $form.find('.select-loader').hide(); $('.troubleshoot-results').show(); } } }); }, 1000); return false; }; return { init: init }; }()); narrowModal = (function(){ var $resultsModal, $narrowForm; var init = function(){ $resultsModal = $('#refine-results-modal'); if($resultsModal.length){ $narrowForm = $('#narrow-results'); addHandlers(); } }; var addHandlers = function(){ $narrowForm.on('submit', fetchResults); }; var fetchResults = function(e){ e.preventDefault(); $('#refine-results-modal').modal('toggle'); var url = $narrowForm.attr('action'); $.ajax({ type: "POST", url: url, data: $narrowForm.serialize(), // serializes the form's elements. success: function(data) { //HANDLE SUCCESS }, error: function(data){ //HANDLE THE ERROR } }); return false; }; return { init: init }; }());// This is placeholder code for predicitve results in the search bar
// You can see this in action on search.php // As of current, this functionality will happen if there is a #predictive-results element Search = (function(){ // Modukle variables var $searchInput, $predictiveList; // Check if we need to initialize var init = function(){ $searchInput = $('#search-input.predictive'); $predictiveList = $('#predictive-results'); if($searchInput.length){ addHandlers(); } }; // add our handlers var addHandlers = function(){ $searchInput.on('keydown', switchToList); $searchInput.on('focus', showList); $predictiveList.on('keydown','a', checkKeymap); $predictiveList.on('click tap','a', changeValue); }; // This code will change focus to the list when the user hits the down arrow var switchToList = function(e){ // Check for down arrow event if(e.keyCode == 40 && $predictiveList.length){ e.preventDefault(); // Find first li in the list and focus it and add a hover class // in some browsers, simply focusing an element does not add a hover state // so we need to do this manully $predictiveList.find('li:first a').trigger('focus').addClass('hover'); } }; var showList = function(e){ // Simple call to show the list $predictiveList.show(); }; var checkKeymap = function(e){ // A switch statement! Wow! switch(e.keyCode){ // Check if down arrow case 40: // Check if the parent is not the last element if(!$(this).parent().is(':last-child')){ $ (this).removeClass('hover').parent().next().find('a').focus().addClass('hover'); } // if it is, nothing should happen return false; //UP // Check if parent li is the first element case 38: if($(this).parent().is(':first-child')){
$(this).removeClass('hover'); //if it is, focus on the search $searchInput.focus(); } else { // if it isnt, then simply iterate up the list $ (this).removeClass('hover').parent().prev().find('a').focus().addClass('hover'); } return false; // Check if 'enter' key is pressed case 13: // trigger a click event to select this value $(this).removeClass('hover'); $(this).trigger('click'); break; };
}
// this is the function that swaps the value from the list to search bar var changeValue = function(e){ $searchInput.val($(this).text()); $predictiveList.hide(); }; return { init: init }; }());Tooltips = (function(){ var $modalTemplate = $('#tooltip-modal'); var init = function(){ if($('.badge-tooltip').length || ($('.with-tooltip').length)){ // Do not remove / modify - Varun. checkBrowser(); } }; var checkBrowser = function(){ if(Modernizr.touch || $(window).width()<768){ addTouchHandlers(); } else { addTouchlessHandlers(); } }; var addTouchlessHandlers = function(){ $('.badge-tooltip').popover({ trigger: 'focus', html: true, container: 'body' }).click(function(e){ if(!$(this).is(':focus')){ e.preventDefault(); $(this).focus(); } }); $('.with-tooltip').popover({ trigger: 'hover',
html: true, container: 'body' }).click(function(e){ if(!$(this).is(':focus')){ e.preventDefault(); $(this).focus(); } }); }; var addTouchHandlers = function(){ $('.badge-tooltip').on('tap click', buildModal); }; var buildModal = function(){ var $badge = $(this); var $modal = $('#tooltip-modal'); if($badge.data('title')){ $modal.find('h3').empty().html($badge.data('title')).show(); } else { $modal.find('h3').hide(); } if ($badge.data('content')){ $modal.find('.content').empty().html($badge.data('content')); showModal(); } }; var showModal = function(){ $modalTemplate.modal(); }; return { init: init }; }());CLC = (function(){ var init = function(){ // After selecting a country, // display that country flag and country name in the next step $('#clc-choose-country .country-options a').on('tap click', function(e) { e.preventDefault(); var selectedCountry = $(this).text(); var selectedCountryFlag = $(this).find('.flag').attr('class'); var totalLanguages = $('#clc-choose-language .language-options li').size(); $('#clc-choose-language').find('#selectedCountry').text(selectedCountry); $('#clc-chooselanguage').find('#selectedCountryFlag').addClass(selectedCountryFlag); // Count the number of supported languages // and display them in the modal-title $('#totalLanguages').text(totalLanguages); }); // When switching from Country to Language, // change the size of the modal from modal-xl to modal-sm $('.country-options a').on('tap click', function(e) { e.preventDefault();
$('#clc-choose-country').hide(); // $('#clc-choose-language').show(); $('#clc-modal').find('.modal-dialog').removeClass('modalxl').addClass('modal-sm'); }); // When switching back from Language to Country, // change the size of the modal back to modal-xl $('#clc-back').on('tap click', function(e) { e.preventDefault(); $('#clc-choose-language').hide(); $('#clc-choose-country').show(); //$('#clc-modal').find('.modal-dialog').removeClass('modalsm').addClass('modal-xl');//do not remove this - Pratisha }); // After clicking on a support language, // add the selected language to the Confirm button and enable it $('#clc-choose-language .language-options a').on('tap click', function(e) { e.preventDefault(); $('#clc-choose-language .language-options a').removeClass('selected'); $(this).addClass('selected'); var selectedLanguage = $(this).text(); $('#selected-language').text(selectedLanguage); $('#confirm-language').removeAttr('disabled'); }); }; return { init: init }; }());PSF = (function(){ var var var var
$window; $footer; $psf; psfHeight;
var init = function(){ if($('#psf').length){ $window = $(window); $footer = $('#footer'); $psf = $('#psf'); psfHeight = $('#psf').height(); addHandlers(); //$('#notifications-trigger').trigger('click'); uncomment this. This is handled in the portlet with session } }; var isMobile = function(){ if(viewport().width <= 800){ return true; } else { return false; } }; function viewport() { var e = window, a = 'inner';
//Please do not
}
if (!('innerWidth' in window )) { a = 'client'; e = document.documentElement || document.body; } return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
var addHandlers = function(){ // $window.on('scroll', checkPos); }; function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; clearTimeout(timeout); timeout = setTimeout(function() { timeout = null; if (!immediate) func.apply(context, args); }, wait); if (immediate && !timeout) func.apply(context, args); }; }; // var checkPos = debounce(function(){ // if($footer){ // var footerPos = $footer.offset().top; // var psfPos = $psf.offset().top + psfHeight; // var windowScroll = $window.scrollTop(); // var windowHeight = $window.height(); // var oldFix; // if(isMobile()){ // oldFix = 0; // } else { // oldFix = 72; // } // if((psfPos > footerPos) || (windowScroll + windowHeight >= $ (document).height())){ // $psf.css({'bottom':'0', 'position':'absolute'}); // } // if(!(psfPos+oldFix <= (windowScroll+windowHeight)) && ($psf.offset().top >= windowScroll)){ // $psf.css({'top':oldFix, 'position':'fixed'}); // } // } // }, 10); var countNotifications = function() { var totalNotifications = $('.notificationsbg').find('.notification').size(); $('#totalNotifications').text(totalNotifications); }; countNotifications(); // Open notifications on click $('#notifications-trigger').on('tap click', function(e) { e.preventDefault();
// Close notifications on click of dismissal $('#dismiss-notifications').on('tap click', function(e) { e.preventDefault(); $(this).attr("aria-hidden","true"); $('.notifications-bg').removeClass('open').addClass('viewed'); $('#notifications-trigger').addClass('viewed'); countNotifications(); // If there no more notifications, show the empty notifications message if ($('.notification').length === 0) { $('#empty-notifications').show(); // Automatically close notifications after 2 sec. setTimeout(function() { $('.notifications-bg').removeClass('open'); }, 2000); } }); var psfWidgetVisible=false; // Toggle the PSF on mobile $('#psf-gripper').on('tap click swipeleft swiperight', function() { //Ios transition hack fix if ($('#psf.open').length) { psfWidgetVisible=false; $('#psf').css('-webkit-transition', 'right 300ms ease-in-out'); setTimeout(function(){ $('#psf').removeAttr('style'); //3439: restore position of PSF setPSFPosition(); }, 300); $('#psf.open #psf-gripper .icon').removeClass('iconrght').addClass('icon-lft'); } else { $('#psf-gripper .icon').removeClass('icon-lft').addClass('iconrght'); //3439: restore position of PSF psfWidgetVisible=true; setPSFPosition(); } $('#psf').toggleClass('open'); }); //3439 start: position psf according to steps bar presence setPSFPosition(); function setPSFPosition(){ var pageIdentifier=$("#pageIdentifier").val(); if($(window).width() < 776){ if($("#steps-bar").is(":visible")){ $("#psf").css("top", "53px"); } else{ $("#psf").css("top", "0px"); }
if(pageIdentifier == "multipleWarranty" || pageIdentifier == "multipleWarrantyResults"){ if(psfWidgetVisible){ $("#psf").css("right", "-41px"); } else{ $("#psf").css("right", "-103%"); } } } else{ $("#psf").css("top", "72px"); if(pageIdentifier == "multipleWarranty" || pageIdentifier == "multipleWarrantyResults"){ $("#psf").css("right", "0px"); } } } //position psf on window resize $(window).resize(function(){ setPSFPosition(); }); //3439 end return { init: init }; }());// This component handles stickyness in the responsive footer // Note, the desktop and mobile header use the same markup Header = function(){ //Set some module variables var $window = $(window); var $header = $('.hp-header'); var $input = $('#search-input'); var init = function(){ addHandlers(); //fire the reset function on load just to sync everything up reset(); // Check cookie to see if users already visted the site, if true then hide the search bar if (!(document.cookie.replace(/(?:(?:^|.*;\s*)hpSession\s*\=\s*([^;]*).*$)| ^.*$/, "$1"))) { if (isMobile()) { $('#hp-search').slideDown(0); $('.mobile-search-toggle').trigger('slideDown'); } } else { if (isMobile()){ $('.mobile-search-toggle').trigger('slideUp'); } } $.cookie('hpSession','true');
}; // check if we are in mobile layout var isMobile = function(){ if(viewport().width <= 800){ return true; } else { return false; } }; // this gives us a better representation of screen width than window.width function viewport() { var e = window, a = 'inner'; if (!('innerWidth' in window )) { a = 'client'; e = document.documentElement || document.body; } return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }; } //this limits a function from firing too many times unecessarily, good for optimization function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; clearTimeout(timeout); timeout = setTimeout(function() { timeout = null; if (!immediate) func.apply(context, args); }, wait); if (immediate && !timeout) func.apply(context, args); }; }; // This function check our scroll position and positions the header correctly // Start HP 453 // This function check our scroll position and positions the header correctly // Depricated: caused buggy input focus when keyboard triggered scroll event on search. // var checkPos = debounce(function () { // if (isMobile()) { // var windowScroll = $window.scrollTop(); // // if we are past 80 pixels, sticky nav // if (windowScroll > 80) { // $header.css({'position': 'fixed', 'top': '0', 'z-index': '999'}); // } else { // // other wise, make it not sticky // $header.css({'position': 'absolute'}); // } // // once we scroll past 80, we want the search bar to pop up, but we dont want it to happen every time we // // scroll, so we limit this functionality between 80 and 120px // // Note: There is a better way to do this, perhaps making use of a libraries .once() function // if (windowScroll > 80 && windowScroll < 120) { // $('.mobile-nav-toggle').removeClass('out'); // $header.find('.mobile-search-toggle').trigger('slideUp'); Leave the search box open and not attached to scroll for keyboards on mobile that trigger
scroll event. // } // } else { // // if we are not in mobile, ensure header is not sticky // $header.css({'position': 'relative'}); // } // }, 10); $window.scroll(function() { var st = scrollY(), changeHeaderAt = 120, $header = $('.hp-header'); var pageTitle = $('#hpProductContextPageTitle'); // Shrink Header only if scrolling down if( st >= changeHeaderAt ) { //pageTitle.hide(); $header.addClass('sticky'); } else { //pageTitle.show(); }
$header.removeClass('sticky');
}); function scrollY() { return window.pageYOffset || document.documentElement.scrollTop; } // End HP 453 // this function fires on window resize, and makes sure all functionality is cleared out between layouts // Not sure why this isnt handled by css classes, surely I had a good reason var reset = debounce(function(){ // if not in mobile, clear out all applied inline styles and change placeholder content //Do not remove - Varun var typeaheadLeftHookDesktop = "0"; var isDesktop = true; if(!isMobile()){ $('#hp-search').hasClass('in') && $('.hp-header .hpsearch').css({'display': 'block'}); $('#psf').insertAfter('#footer');/*Moved this to site.js VV */ //removed as it hides the H1 tag when browser is resized // $('#body').css({'padding-top': '0'}); //Do not remove - Varun $(".search-input").each(function(){ $(this).attr("ghosttext",$(this).data("placeholderlg")); if($(this).val()==$(this).data("placeholdersm") ){ // removed the null check as keeping it on null made ghost text editable while size changed on focus $(this).val($(this).data("placeholderlg")); } typeaheadLeftHookDesktop = $(this).parents(".searchbg").find("#search-dropdown").innerWidth() + 15; $(this).siblings(".typeaheadHook").val(typeaheadLeftHookDesktop);
// do not uncomment - Varun $('.hp-header #searchinput').attr('placeholder', 'Enter your product number, a question or keywords'); // if it is mobile, apply mobile styling and change search box placeholder content } else { // $header.css({'position': 'absolute'}); // now handled by .sticky in _hp-navigation.less // $('#body').css({'padding-top': '60px'}); //moved to _hpstructure.less //for positioning the widgets in mobile devices :: Pratisha $('#psf').appendTo('.fixedWidgets'); //Do not remove - Varun $(".search-input").each(function(){ $(this).attr("ghosttext",$(this).data("placeholdersm")); if(!($(this).is(":focus"))){ if($(this).val()==$(this).data("placeholderlg") ){ $(this).val($(this).data("placeholdersm")); } typeaheadLeftHookDesktop = $ (this).siblings(".typeaheadHook").val(); $(this).siblings(".typeaheadHook").val("0")
// do not uncomment - Varun $('.hp-header #search-input').attr('placeholder', 'Search HP Support'); } }, 10); // this is a simple handler to clear text out of search box var clearSearch = function(){ //modified by Varun do not change
$('.hp-header #search-input').val($('.hp-header #searchinput').attr("ghosttext")); $('.hp-header #search-input').addClass("placeholderText"); }; // add our event handlers var addHandlers = function(){ //$window.on('scroll', checkPos); $window.on('resize', reset); //Do not remove - Varun //$('#clear-search').on('tap click', clearSearch); $('.mobile-nav-toggle').on('click', function(){ $('.mobile-search-toggle').trigger('slideUp'); }); $('.mobile-search-toggle-close').on('click', clearSearch); //added by varun $('.mobile-search-toggle').on('tap click', function(){ $('.mobile-nav-toggle').trigger('dClose'); }); }; return { init: init, isMobile:isMobile, viewport:viewport, debounce:debounce }; }();/* Modified by Pavan Kamath Do not merge Modified By AA to add accessibility for the page */ Tabs = (function(){ var $toggles; var init = function(){ if($('[data-toggle="tab"]').length){ addHandlers(); $toggles = $('[data-toggle="tab"]'); checkState(); initCurrentURL(); } } var initCurrentURL = function(){ productSeries = $('#productSeries').val(); modelDetails = $('#modelDetails').val(); productNameOid = $('#productSeriesId').val(); // UAT defect fix: undefined is appending in url after clicking on homepage tabs var identifier = $('#pageIdentifier').val(); if( identifier == "Product Details Page"){ currentURL = "/"+getCCLC('cc')+"-"+getCCLC('lc') +"/product/"+productSeries+"/"+productNameOid; if(modelDetails!=""){ currentURL = currentURL + "/model/" + modelDetails; }
} if(identifier == "caseCreation"){ currentURL = window.location.href; } } var addHandlers = function(){ $('[data-toggle="tab"]').on('tap click', pushState); $('[data-toggle="tab"]').on('showTab', showTab); $('[data-toggle="tab"]').on('hideTab', hideTab); window.setTimeout(function () { window.addEventListener("popstate", function (e) { checkState(); }, false); }, 1); } var pushState = function(){ var activelink = $(this).attr("id"); if($("#pageIdentifier").val() == "caseCreation"){ link = currentURL; } else{ link = currentURL + '/' + activelink; }
}
//Remove query parametes as they will never come again if( location.href.indexOf('?')>0){ var queryparams = location.href.split('?'); link = link + '?' +queryparams[1]; } history.pushState(null, null, link); checkState(); //console.log('setCanonicalUrl called from tabs.js.....'); setCanonicalUrl();
var checkState = function(){ var $toggle = getActiveTabFromURL(); if($toggle.parent().hasClass('active')) return; $('.tab-content.col-lg16>div.active').removeClass('active').addClass('fade'); $toggle.trigger('showTab'); $toggles.not($toggle).trigger('hideTab'); } var hideTab = function(){ var $toggle = $(this); if(!$toggle.parent().hasClass('active')) return; $toggle.parent().removeClass('active'); $toggle.parent().attr({"tabindex" : "-1"}); var $tabContent = $($toggle.attr('href')); $tabContent.removeClass('active'); $tabContent.attr({"tabindex" : "-1"}); $tabContent.attr('aria-hidden', 'true');
} var showTab = function(){ var $toggle = $(this); $(".tab").removeClass("active"); $toggle.parent().addClass('active'); $toggle.parent().attr({"tabindex" : "0"}); var activelink = $(this).attr("id"); // if(activelink == "drivers"){ // if(typeof currentURL == "undefined" || currentURL == null || currentURL == ""){ // initCurrentURL(); // } // link = currentURL + '/'; // //Remove query parametes as they will never come again // if( location.href.indexOf('?')>0){ // var queryparams = location.href.split('?'); // link = link + '?' +queryparams[1]; // } // history.replaceState(null, null, link); // setCanonicalUrl(); // } var $tabContent = $($toggle.attr('href')); $tabContent.addClass('active'); $tabContent.attr({"tabindex" : "0"}); $tabContent.attr('aria-hidden', 'false'); } var getActiveTabFromURL = function(){ var tabString = "solutions+drivers+troubleshooting+how-to+productinfo+manuals+videos+more-options"; var removeHash = location.href.split("#"); var urllocation = removeHash[0].split("/"); //support for query Params urllocation = urllocation[urllocation.length-1].split("?"); var identifyActiveTab = ""; currentTab = ''; if(tabString.indexOf(urllocation[0])>0){ currentTab = $("#"+urllocation[0]); if(!currentTab.is(':visible')){ currentTab = $('[data-toggle=tab]:visible').first(); currentTab.attr({"tabindex" : "0"}); } } else{
var stepsLabel = function(){ var $container = $('div#guided #steps-bar'); var $list = $('div#guided #steps-bar li'); switch (step){ case 1: case 2: case 3: $list.first().removeClass('next'); break; case 4: case 5: case 7: case 8: case 9: case 10: $list.first().addClass('done'); $list.eq(1).removeClass('next'); break; case 6: $list.eq(1).addClass('done'); $list.eq(2).removeClass('next'); break; } }; var showNext = function(e){ $('#step-' + step).addClass('hidden'); step++; $('#step-' + step).removeClass('hidden'); stepsLabel();
};
if (step == 6) { changeTitle1(); }
var changeTitle1 = function(){ $('#swd-title').text('Thank you for using the HP guided experience for your software and drivers'); $('#swd-title-text').remove(); }; var handleUncheck = function(e){ var self = this; if (!this.checked && this.value == 1) { $('#driver-download-warning').modal('toggle'); $('.cancel').unbind().on('click', function(){ $(self).click(); }); } if (!$('.download-list .list-body input').is(':checked')) { $('.download-list .button').addClass('button-disabled').unbind(); } else { $('.download-list .button').removeClass('buttondisabled').on('click',showProgressBar); } }; var resetStep3 = function(e) { e.preventDefault(); step = 2; showStep3(); }; var showStep3 = function(){ var $items = $('#step-3 .selection-group .product-selection'); var finishLoading = 6000; $('#step-3 .progress-bar-component').show(); $('#found-count').html('(0)'); $('#network-count').html('(0)'); $('#step-3 .header1').removeClass('hidden'); $('#step-3 .header2').addClass('hidden'); window.runProgressBar(); if (timeout) { clearTimeout(timeout); } $items.hide(); showNext(); $items.each(function(index, el){ setTimeout(function(){ $('#found-selections').removeClass('hidden'); }, finishLoading / 4); setTimeout(function(){ $('#network-selections').removeClass('hidden'); }, finishLoading / 2); setTimeout(function(){ $(el).show(); var $network = $('#network-selections .productselection:visible');
var showLoading = function(e){ e.preventDefault(); showNext(); setTimeout(showNext,4000); }; var showProgressBar = function(){ window.runProgressBar(); setTimeout(showNext,6000); showNext(); }; return { init: init }; }());OsSelector = (function(){ var init = function(){ if ($('#os-selector').length) { /* added as a part of new build during merge. Needs to be validated $('#os-selector').hide(); $('#os-heading2').hide();*/ addHandlers(); } }; var addHandlers = function(){ $('#os-update').on('click', updateOs); $('#os-heading1').on('click', wordHandler); $('#os-heading2').on('click', xHandler); /* added as a part of new build. Pratisha to validate $('#os-word-trigger').on('click', wordHandler); $('#os-x-trigger').on('click', xHandler);*/ $('.fancy-select .trigger').on('click', dropdownHandler); }; var dropdownHandler = function(e){ $('.fancy-select .trigger + .options').not($(this)).not($ (this).next()).removeClass('open'); }; var xHandler = function(){ $("#os-heading1").css("pointer-events","none"); $('#os-heading1').show(); $('#os-heading2').hide();
};
$('#os-x-trigger').show();
var wordHandler = function(){ $("#os-heading2").css("pointer-events","none"); $('#os-heading2').show(); $('#os-heading1').hide(); $('#os-selector').show(); }; var updateOs = function(e){ e.preventDefault(); var resultArray = $('#os-selector').serializeArray(); $.each(resultArray, function(index, value){ console.log(value); var platform = 'os-' + value.name; var text = value.value; $('#'+platform).html(text); }); $('#os-selector').removeClass('in').slideUp(); $('.os-selector-trigger').removeClass('toggled'); $('#os-heading2').hide(); $('#os-heading1').show(); }; return { init : init }; })();DownloadTable = (function(){ var init = function(){ if ($('.download-table').length){ addHandlers(); } }; var addHandlers = function() { $('#download-table .swd-dropdown').on('click', swdDropdown); $('a.accordionTitle').on('click', featuredDriverShow); /*VV*/ }; /* featuredDriver and swdDropdown function moved to swdAccordion.js in the portlet VV*/ /*AA - function ends here*/ var sort = function(ev){ var reverse; var $this = $(this); var sortCat = $this.data('sort-trigger'); var $toggles = $('#sortable-table .panel'); ev.preventDefault(); $('[data-sorttrigger]').removeClass('active').parent().removeClass('active'); $('[data-sort-trigger]').not($(this)).removeClass('reverse'); $this.addClass('active').parent().addClass('active'); $this.hasClass('reverse') ? reverse = true : reverse = false $toggles.each(function(index){ var sortEls = $(this).find('[data-sort="'+sortCat+'"]'); sortEls.sort(function(a,b){ var result; if (sortCat === 'date') {
a = new Date($(a).html()); b = new Date($(b).html()); } else { a = $(a).html(); b = $(b).html(); } if (a > b) { result = 1; } else if (a < b) { result = -1; } else { result = 0; } return reverse ? result : -result;
}; var mobileSort = function(ev){ var $this = $(this); var sortCat = $this.data('mobile-trigger'); var reverse = $this.data('reverse'); var $toggles = $('#sortable-table .panel'); }; return { init : init }; }());$(document).ready(function(){ var set_tab = function(tab_container_id, tab_id){ $('#' + tab_container_id + ' ul li').removeClass('active'); // Now add class "active" to the selected/clicked tab $('#' + tab_container_id + ' a[rel="'+tab_id+'"]').parent().addClass("active"); $('#' + tab_container_id + '-content .tab-pane').removeClass("active").hide();
}
// Show the selected tab content $('#' + tab_container_id + '-content #' + tab_id).addClass("active").fadeIn();
// Function that gets the hash from URL var get_hash = function(){ if (window.location.hash) { // Get the hash from URL var url = window.location.hash; // Remove the # var current_hash = url.substring(1);
// Split the IDs with comma var current_hashes = current_hash.split(","); $.each(current_hashes, function(i, v){ set_tab($('a[rel="'+v+'"]').parent().parent().parent().attr('id'), v); }); }
}
// Called when page is first loaded or refreshed get_hash(); // Looks for changes in the URL hash $(window).bind('hashchange', function() { get_hash(); }); // Called when we click on the tab itself $('.tab-box ul li').click(function() { var tab_id = $(this).children('a').attr('rel'); // Update the hash in the url window.location.hash = tab_id; // Do nothing when tab is clicked return false; }); });/* ======================================================================== * Bootstrap: modal.js v3.0.2 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$element = $(element) this.$backdrop = this.isShown = null if (this.options.remote) this.$element.load(this.options.remote)
} Modal.DEFAULTS = { backdrop: true , keyboard: true , show: true } Modal.prototype.toggle = function (_relatedTarget) { return this[!this.isShown ? 'show' : 'hide'](_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.$element.on('click.dismiss.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) // don't move modals dom position } that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one($.support.transition.end, function () { that.$element.focus().trigger(e) }) .emulateTransitionEnd(300) : that.$element.focus().trigger(e)
}) }
Modal.prototype.hide = function (e) {
if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one($.support.transition.end, $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.focus() } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keyup.dismiss.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null }
Modal.prototype.backdrop = function (callback) { this.options.backdrop = 'static' var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('') .appendTo(document.body) this.$element.on('click.dismiss.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback()
}
} else if (callback) { callback() }
// MODAL PLUGIN DEFINITION // ======================= var old = $.fn.modal $.fn.modal = function (option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) })
}
$.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s] +$)/, ''))) //strip for ie7 var option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option, this) .one('hide', function () { $this.is(':visible') && $this.focus() })
})
$(document) .on('show.bs.modal', '.modal', function () { $(document.body).addClass('modalopen') }) .on('hidden.bs.modal', '.modal', function () { $ (document.body).removeClass('modal-open') }) }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.0.2 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames 'WebkitTransition' : , 'MozTransition' : , 'OTransition' : , 'transition' : }
"); } } }); }; sel.on('update.fs', function() { wrapper.find('.options').empty(); return copyOptionsToList(); }); return copyOptionsToList(); }); }; }).call(this);/** * * Version: 0.0.8 * Author: Gianluca Guarini * Contact: [email protected] * Website: http://www.gianlucaguarini.com/ * Twitter: @gianlucaguarini * * Copyright (c) 2013 Gianluca Guarini * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. **/ (function(doc, win) { 'use strict'; if (typeof doc.createEvent !== 'function') return false; // no touch events here // helpers var useJquery = typeof jQuery !== 'undefined', isTouch = !!('ontouchstart' in window) && navigator.userAgent.indexOf('PhantomJS') < 0, setListener = function(elm, events, callback) { var eventsArray = events.split(' '), i = eventsArray.length; while (i--) { elm.addEventListener(eventsArray[i], callback, false); }
}, getPointerEvent = function(event) { return event.targetTouches ? event.targetTouches[0] : event; }, sendEvent = function(elm, eventName, originalEvent, data) { var customEvent = doc.createEvent('Event'); data = data || {}; data.x = currX; data.y = currY; data.distance = data.distance; if (useJquery) jQuery(elm).trigger(eventName, data); else { customEvent.originalEvent = originalEvent; for (var key in data) { customEvent[key] = data[key]; } customEvent.initEvent(eventName, true, true); elm.dispatchEvent(customEvent); } }; var touchStarted = false, // detect if a touch event is sarted swipeTreshold = win.SWIPE_TRESHOLD || 80, taptreshold = win.TAP_TRESHOLD || 50, precision = win.TAP_PRECISION / 2 || 60 / 2, // touch events boundaries ( 60px by default ) tapNum = 0, currX, currY, cachedX, cachedY, tapTimer; // shall we use it just on the touch devices? // by default Tocca.js detects also the mouse events isTouch = true; //setting the events listeners
setListener(doc, isTouch ? 'touchstart' : 'mousedown', function(e) { var pointer = getPointerEvent(e); // caching the current x cachedX = currX = pointer.pageX; // caching the current y cachedY = currY = pointer.pageY; // a touch event is detected touchStarted = true; tapNum ++; // detecting if after 200ms the finger is still in the same position clearTimeout(tapTimer); tapTimer = setTimeout(function() { if ( cachedX >= currX - precision && cachedX <= currX + precision && cachedY >= currY - precision && cachedY <= currY + precision && !touchStarted ) { // Here you get the Tap event sendEvent(e.target, (tapNum === 2) ? 'dbltap' : 'tap', e); } tapNum = 0; }, taptreshold); }); setListener(doc, isTouch ? 'touchend' : 'mouseup', function(e) { var eventsArr = [], deltaY = cachedY - currY, deltaX = cachedX - currX; touchStarted = false; if (deltaX <= -swipeTreshold) eventsArr.push('swiperight'); if (deltaX >= swipeTreshold) eventsArr.push('swipeleft'); if (deltaY <= -swipeTreshold) eventsArr.push('swipedown'); if (deltaY >= swipeTreshold) eventsArr.push('swipeup'); if (eventsArr.length) { for (var i = 0; i < eventsArr.length; i++) { var eventName = eventsArr[i]; sendEvent(e.target, eventName, e,{ distance:{ x:Math.abs(deltaX), y:Math.abs(deltaY) } }); } }
}(document, window));/* ======================================================================== * Bootstrap: tooltip.js v3.0.2 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.DEFAULTS = { animation: true , placement: 'top' , selector: false , template: '
if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.'+ this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) if (e.isDefaultPrevented()) return var $tip = this.tip() this.setContent() if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) {
var $parent = this.$element.parent() var orgPlacement var docScroll document.body.scrollTop var parentWidth $parent.outerWidth() var parentHeight $parent.outerHeight() var parentLeft $parent.offset().left
Tooltip.prototype.applyPlacement = function(offset, placement) { var replace var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft $tip .offset(offset) .addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight
Tooltip.prototype.replaceArrow = function(delta, dimension, position) { this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + "%") : '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle()
}
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right')
Tooltip.prototype.hide = function () { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one($.support.transition.end, complete) .emulateTransitionEnd(150) : complete()
Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : }
o.title)
return title
Tooltip.prototype.tip = function () { return this.$tip = this.$tip || $(this.options.template) } Tooltip.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow') } Tooltip.prototype.validate = function () { if (!this.$element[0].parentNode) {
} Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = e ? $(e.currentTarget)[this.type] (this.getDelegateOptions()).data('bs.' + this.type) : this self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { this.hide().$element.off('.' + this.type).removeData('bs.' + this.type) } // TOOLTIP PLUGIN DEFINITION // ========================= var old = $.fn.tooltip $.fn.tooltip = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }
})
$.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /** * jquery.matchHeight.js v0.5.2
* http://brm.io/jquery-match-height/ * License: MIT */ (function($) { $.fn.matchHeight = function(byRow) { // handle matchHeight('remove') if (byRow === 'remove') { var that = this; // remove fixed height from all selected elements this.css('height', ''); // remove selected elements from all groups $.each($.fn.matchHeight._groups, function(key, group) { group.elements = group.elements.not(that); }); // TODO: cleanup empty groups return this;
}
if (this.length <= 1) return this; // byRow default to true byRow = (typeof byRow !== 'undefined') ? byRow : true; // keep track of this group so we can re-apply later on load and resize events
$.fn.matchHeight._groups.push({ elements: this, byRow: byRow }); // match each element's height to the tallest element in the selection $.fn.matchHeight._apply(this, byRow); return this;
}; $.fn.matchHeight._apply = function(elements, byRow) { var $elements = $(elements), rows = [$elements]; // take note of scroll position var scrollTop = $(window).scrollTop(), htmlHeight = $('html').outerHeight(true); // get rows if using byRow, otherwise assume one row if (byRow) { // must first force an arbitrary equal height so floating elements break evenly
$.each(rows, function(key, row) { var $row = $(row), maxHeight = 0; // ensure elements are visible to prevent 0 height var hiddenParents = $row.parents().add($row).filter(':hidden'); hiddenParents.css({ 'display': 'block' }); // iterate the row and find the max height $row.each(function(){ var $that = $(this), display = $that.css('display') === 'inline-block' ? 'inlineblock' : 'block'; // ensure we get the correct actual height (and not a previously set height value) $that.css({ 'display': display, 'height': '' }); // find the max height (including padding, but not margin) if ($that.outerHeight(false) > maxHeight) maxHeight = $that.outerHeight(false);
// revert display block hiddenParents.css({ 'display': '' }); // iterate the row and apply the height to all elements $row.each(function(){ var $that = $(this),
verticalPadding = 0; // handle padding and border correctly (required when not using
// set the height (accounting for padding and border) $that.css('height', maxHeight - verticalPadding);
}); // restore scroll position if enabled if ($.fn.matchHeight._maintainScroll) $(window).scrollTop((scrollTop / htmlHeight) * $ ('html').outerHeight(true)); return this; }; /* * _applyDataApi will apply matchHeight to all elements with a data-matchheight attribute */ $.fn.matchHeight._applyDataApi = function() { var groups = {}; // generate groups by their groupId set by elements using data-match-height $('[data-match-height], [data-mh]').each(function() { var $this = $(this), groupId = $this.attr('data-match-height') || $this.attr('data-mh'); if (groupId in groups) { groups[groupId] = groups[groupId].add($this); } else { groups[groupId] = $this; } });
};
// apply matchHeight to each group $.each(groups, function() { this.matchHeight(true); });
/* * _update function will re-apply matchHeight to all groups with the correct options */ $.fn.matchHeight._groups = []; $.fn.matchHeight._throttle = 80; $.fn.matchHeight._maintainScroll = false; var previousResizeWidth = -1,
updateTimeout = -1; $.fn.matchHeight._update = function(event) { // prevent update if fired from a resize event // where the viewport width hasn't actually changed // fixes an event looping bug in IE8 if (event && event.type === 'resize') { var windowWidth = $(window).width(); if (windowWidth === previousResizeWidth) return; previousResizeWidth = windowWidth; } // throttle updates if (updateTimeout === -1) { updateTimeout = setTimeout(function() { $.each($.fn.matchHeight._groups, function() { $.fn.matchHeight._apply(this.elements, this.byRow); }); updateTimeout = -1; }, $.fn.matchHeight._throttle); };
}
/* * bind events */ // apply on DOM ready event $($.fn.matchHeight._applyDataApi); // update heights on load and resize events $(window).bind('load resize orientationchange', $.fn.matchHeight._update); /* * rows utility function * returns array of jQuery selections representing each row * (as displayed after float wrapping applied by browser) */ var _rows = function(elements) { var tolerance = 1, $elements = $(elements), lastTop = null, rows = []; // group elements by their top position $elements.each(function(){ var $that = $(this), top = $that.offset().top - _parse($that.css('margin-top')), lastRow = rows.length > 0 ? rows[rows.length - 1] : null; if (lastRow === null) { // first item on the row, so just push it rows.push($that); } else {
}
});
// if the row top is the same, add to the row group if (Math.floor(Math.abs(lastTop - top)) <= tolerance) { rows[rows.length - 1] = lastRow.add($that); } else { // otherwise start a new row group rows.push($that); }
// keep track of the last row top lastTop = top;
return rows; }; var _parse = function(value) { // parse value and convert NaN to 0 return parseFloat(value) || 0; }; })(jQuery);/*! * jQuery Cookie Plugin v1.4.1 * https://github.com/carhartl/jquery-cookie * * Copyright 2006, 2014 Klaus Hartl * Released under the MIT license */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD define(['jquery'], factory); } else if (typeof exports === 'object') { // CommonJS factory(require('jquery')); } else { // Browser globals factory(jQuery); } }(function ($) { var pluses = /\+/g; function encode(s) { return config.raw ? s : encodeURIComponent(s); } function decode(s) { return config.raw ? s : decodeURIComponent(s); } function stringifyCookieValue(value) { return encode(config.json ? JSON.stringify(value) : String(value)); } function parseCookieValue(s) { if (s.indexOf('"') === 0) { // This is a quoted cookie as according to RFC2068, unescape... s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
} try {
}
// Replace server-side written pluses with spaces. // If we can't decode the cookie, ignore it, it's unusable. // If we can't parse the cookie, ignore it, it's unusable. s = decodeURIComponent(s.replace(pluses, ' ')); return config.json ? JSON.parse(s) : s; } catch(e) {}
function read(s, converter) { var value = config.raw ? s : parseCookieValue(s); return $.isFunction(converter) ? converter(value) : value; } var config = $.cookie = function (key, value, options) { // Write if (arguments.length > 1 && !$.isFunction(value)) { options = $.extend({}, config.defaults, options); if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new
Date();
}
t.setTime(+t + days * 864e+5);
return (document.cookie = [ encode(key), '=', stringifyCookieValue(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // Read var result = key ? undefined : {}; // To prevent the for loop in the first place assign an empty array // in case there are no cookies at all. Also prevents odd result when // calling $.cookie(). var cookies = document.cookie ? document.cookie.split('; ') : []; for (var i = 0, l = cookies.length; i < l; i++) { var parts = cookies[i].split('='); var name = decode(parts.shift()); var cookie = parts.join('='); if (key && key === name) { // If second argument (value) is a function it's a converter...
result = read(cookie, value); break;
} // Prevent storing a cookie that we couldn't decode. if (!key && (cookie = read(cookie)) !== undefined) { result[name] = cookie; } } };
return result;
config.defaults = {}; $.removeCookie = function (key, options) { if ($.cookie(key) === undefined) { return false; }
};
// Must not alter options, thus extending a fresh object... $.cookie(key, '', $.extend({}, options, { expires: -1 })); return !$.cookie(key);
}); } /*create markup for os facets */ function paintOSFacets(osFacets) { var hierarchyLevel1Ct = 0; for(var hierarchyLevel1 in osFacets) { var hierarchyLevel2 = osFacets[hierarchyLevel1]; var level2Label, level2Id; // for upto 5 products if(hierarchyLevel1Ct<5) { $('div#osFacets ul.filter-level-1') .append('
'); } else { // for more than 5 records $('div#osFacets ul.filter-level-1') .append('
/*to create params for ajax call for pagination and facets search - Richa*/ function facetsPaginationParams(pageNum) { var var var var var var var var var
/*called on click of facets - ajax call to reload search and pagination - Richa*/ function facetsAjax() { var ajaxParam = facetsPaginationParams(1); var requestJson = JSON.stringify(ajaxParam.paramData); var pageURL = $('#paginationURL').val(); callAjaxUtil("facets",pageURL,"POST",parsePaginationJson,"JSON", requestJson, }
/*called on click of View English results - ajax call to reload search and pagination - Sushmita*/ function englishResultsAjax(searchLc) { var ajaxParam = facetsPaginationParams(1); ajaxParam.paramData["lc"] = searchLc; var requestJson = JSON.stringify(ajaxParam.paramData); var pageURL = $('#paginationURL').val(); callAjaxUtil("facets",pageURL,"POST",parsePaginationJsonEnglish,"JSON", requestJson, null,null,null,true,handleLoadingResult,true,handleLoadingResult,false); } function localResultsAjax(searchLc) { var ajaxParam = facetsPaginationParams(1); ajaxParam.paramData["lc"] = searchLc; var requestJson = JSON.stringify(ajaxParam.paramData); var pageURL = $('#paginationURL').val(); callAjaxUtil("facets",pageURL,"POST",parsePaginationJsonLocale,"JSON", requestJson, }
// hide facets in case of less than 10 results function hideFacets() { $('#filters-block').css('visibility','hidden'); $('#lessResultsText').hide(); $("#filter-trigger").hide(); $('#narrow-search-results').hide(); $('.filter-header').hide(); } /* For os facet pre-population which is selected by user from 300 modal popup */ function osPrePopulation() {
var selectedModalVal = $("#interstitialSearchOSL1").val(); if(selectedModalVal!="") { var allOSFacets = $("#osFacets").find('input[type="hidden"]'); var tobeSelectedFacet, selectedFacetSection; $.each(allOSFacets, function(index, obj) { if($(obj).val() == selectedModalVal) { tobeSelectedFacet = $(obj).parent(); selectedFacetSection = tobeSelectedFacet.parents('.filteroptions-nested'); tobeSelectedFacet.find('.checkbox').prop('checked',true); // making actual hidden checkbox checked tobeSelectedFacet.find('.icheckbox_flatblue').addClass('checked'); // making css created checkbox checked osPrePopulateClearFilter(); // showing selected facet in clear facets section selectedFacetSection.show(); // open selected facet custom heirarcy level 1 section selectedFacetSection.siblings('.expandable').addClass('selected'); changing icon to expanded } }); } }
//
function osPrePopulateClearFilter() { $('.filter-options input[type="checkbox"]').not('[datafilter="all"]').each(function(){ var $input = $(this); var $filterList = $('.applied-filters'); if($input.prop('checked')){ var $tag = $(document.createElement('li')); var $button = $(document.createElement('button')); var parentTitle = $(this).parents('.filtercategory').children('.filter-title').html(); var title; var categoryList; $button.addClass('filter-close icon').attr('ref', $input.attr('class').split(' ').pop()); $tag.text($(this).parents('label').text()).attr('ref', $input.attr('class').split(' ').pop()).addClass('applied-filtersitem').prepend($button); if ($('.filter-selected-title[data-selected-title="' + parentTitle + '"]').length){ $('.filter-selected-title[data-selected-title="' + parentTitle + '"]').append($tag); } else { title = $(document.createElement('li')).html(parentTitle); categoryList = $ (document.createElement('ul')).addClass('filter-selected-title').attr('dataselected-title',parentTitle).append(title).append($tag); $filterList.append(categoryList); } SCF.initElem($tag); } $('.applied-filters').show(); });
} //Document Created on 30/March/2015 //This is to prevent all the portlet's title being read via screen reader. $('document').ready(function(){ var ariaTimer = window.setInterval(function(){ $(".ibmPortalControl").attr("aria-labelledby"," "); //console.log('aria lablelled'); window.clearInterval(ariaTimer); }, 1000 );
/*search Blue dropdown */ // $("#search-dropdown") // .on("click",function(){ // $("#searchDdDivAT.dropdown").toggleClass("open") // }) // .on("mousedown",function(e){ // if(e.which==1)$("#searchDdDivAT.dropdown").toggleClass("open") // }) }); // communities link /* * commenting this as after code merge, the focus is coming inherently $( "#navCommunities" ).focus(function() { $(this).css( "outline-width", "5px" ).css( "outline-style", "auto" ).css( "outline-color", "#4d90fe" ); }); $( "#navCommunities" ).focusout(function() { $(this).css( "outline-width", "" ).css( "outline-style", "" ).css( "outlinecolor", "" ); });*/var isUserLoggedIn = false; var isUserAdxLoggedIn = false; var hpUserProfileObject = {}; var $userEmail = $('#HPPEmailId'); var $CRM_CDX_URL = $('#CRM_CDX_URL'); // Create business account in register/sign in modal function redirectToHPSALogin(){ //Funtion that redirects to HPSA login var domain = window.location.origin; var url = domain + "/hp-pps-services/auth/login?cc=" + getCCLC("cc") + "&lc=" + getCCLC("lc") + "&pageurl=" + window.location.href; window.open(url, "_self"); } /*
Create dynamic menu item and append to sign in menu @Param: data:{array} - contain link objects with URL and name attribute */ function createDynamicMenu(data) { if (data) { var $menuHolder = $("#signInOrEditMob"); for (var item in data) { var newMenuItem = document.createElement('div'); newMenuItem.className = "mobMenuElement"; newMenuItem.appendChild(createLink(data[item])); } }
$menuHolder.append(newMenuItem);
}
/* Create dynamic anchor element for passed item. @Param: accept data object with name and url properties @ return: anchor element
*/ function createLink(item) { var a = document.createElement('a'); var linkText = document.createTextNode(item.name); a.appendChild(linkText); a.href = item.url; return a; } $("document").ready(function(){ paintWelcomeHeader();
// defined in head.jsp if(signOutMenuOptions && $.parseJSON(signOutMenuOptions) && $.parseJSON(signOutMenuOptions).menuOptions){ }
function readCookie(key){ cookieName = key+"="; cookieArray = document.cookie.split(";"); var numberOfMatch = 0; for(i=0; i= 0){ var indexOfEq = cookieArray[i].indexOf("="); var value = cookieArray[i].substr((indexOfEq+1), (cookieArray[i].length-1)); numberOfMatch += 1; if(value !=""){ return value; } else{ return null; }
}
} } if(numberOfMatch == 0){ return null }
if ($userEmail.val() !== "null" && $userEmail.val() != undefined) { if($userEmail.val().length > 0){ $('#modalLoginTxt').val($userEmail.val()); $('#login-modal').modal('show'); } } // click event for after sign in menu for mobile and desktop $("#welcomeMessageNew").on("click", function () { if ($("#profileUtilityMenuMob").is(":visible")){ $("#profileUtilityMenuMob").slideUp("fast"); $(".welcomeOverlay").slideUp(); $("#welcomeUserLink i.hidden-lg").removeClass("iconup").addClass("icon-dwn"); $("#welcomeUserLink i.fa-caret-up").removeClass("fa-caretup").addClass("fa-caret-down"); $("body").css("overflow", "auto"); } else{ $("#profileUtilityMenuMob").slideDown("fast"); $("body").animate({ scrollTop: "0px" }, 100); $("body").animate({ scrollTop: "0px" }, 100, function () { $(".welcomeOverlay").slideDown(); if ($(window).innerWidth() < 786){ // overflow hidden only for mobile $("body").css("overflow", "hidden"); $("#welcomeUserLink i.hidden-lg").removeClass("icondwn").addClass("icon-up"); } }); $("#welcomeUserLink i.fa-caret-down").removeClass("fa-caretdown").addClass("fa-caret-up"); } }); // Overlay click event to toggle icon class and close overlay $(".welcomeOverlay").on("click", function(){ $("#welcomeUserLink i.hidden-lg").removeClass("iconup").addClass("icon-dwn"); $("#profileUtilityMenuMob").slideUp("fast"); $(".welcomeOverlay").slideUp(); $("body").css("overflow","auto"); }); // signout button click calling method $("#signOutLinkMob").on("click", function () { var domain = window.location.origin; var url = domain + '/hp-pps-services/auth/logout?cc=' + getCCLC("cc") + "&lc=" + getCCLC("lc") + "&pageurl=" + window.location.href ; window.open(url, "_self"); // open in new tab });
// edit profile button click calling method $("#editProfileLinkMob").on("click", function () { var domain = window.location.origin; var url = domain + '/hp-pps-services/auth/editprofile?cc=' + getCCLC("cc") + "&lc=" + getCCLC("lc") + "&pageurl=" + window.location.href; //window.open(url, "_self"); //Open Edit Profile Window in new Tab -- HPID window.open(url); }); if(readCookie("HPPSESSION") != null || readCookie("SMSESSION") != null){ //getUserProfile(); } $(document).on("click", "#btnCreatePersonalAC", function () { var lc = getCCLC("lc"); var cc = getCCLC("cc"); var domain = window.location.origin; var url = domain + '/hp-pps-services/auth/registration?cc=' + cc + '&lc=' + lc + "&pageurl=" + window.location.href; window.open(url, "_self"); });
});
$(document).on("click", "#btnCreateBusinessAC", function () { if ($CRM_CDX_URL.val().length > 0) { window.open($CRM_CDX_URL.val(), "_self"); }
}); /** * */ function paintWelcomeHeader(){ if (typeof profileDetails !== 'undefined' && profileDetails && (profileDetails.firstName || profileDetails.lastName)) { if(profileDetails.signOutLink){ $("#signOutLinkMob").attr("href",profileDetails.signOutLink); } if(profileDetails.editProfileLink){ $("#editProfileLinkMob").attr("href",profileDetails.editProfileLink); } isUserLoggedIn = true; // // hide sign in/register // $(".signInRegisterLink").addClass("hide"); // // show welcome user message // $("#welcomeUserLink").removeClass("hide"); // $("#welcomeHeader").show(); //adding code same as splitSearchBox.js for header var $userName = $(".userFirstName"); var cc = getCCLC("cc");
var userName; //Story R183-222- Display lastname+firstname+title for few locales if (cc == 'jp' || cc == 'kr' || cc == 'cn' || cc == 'tw' || cc == 'hk') {
// R182-70 - set the checkTime flag and start the timer handleTorontoTimer("start"); // R182-69 - save SN and PN in localstorage if page is product contextual handleProductContext("save"); // dismiss chat prompt dismissChatPrompt(); handleHoverText("unbind");
function loadChatBotIframe(token){ var iframeInstance = $("iframe.torontoChatBotIframe"); var chatBotUrlForIframe; if(isMobileDevice()) { chatBotUrlForIframe = chatBotUrlMobile; } else { chatBotUrlForIframe = chatBotUrl; } // if there are other query strings added to the bot // iframe URL via SSC (e.g. for debugging) if(chatBotUrlForIframe.indexOf("?")>=0){ // append a & instead of ?, if needed if(chatBotUrlForIframe.charAt(chatBotUrlForIframe.length-1)!="&"){ chatBotUrlForIframe = chatBotUrlForIframe.concat("&"); } }else{ // no query strings added yet chatBotUrlForIframe = chatBotUrlForIframe.concat("?"); }
}
// append token var iframeSrc = chatBotUrlForIframe+"t="+token; iframeInstance.attr("src", iframeSrc);
/** * @param iframeInstance
*/ function insertChatBotIframe(iframeInstance){ // if the chat bot iframe has loaded if($(iframeInstance).attr("src") != undefined){ // show a spinner hideLoadingSpinner(); // show the bot frame $(".torontoChatBotIframe").removeClass("hideChatbot"); $("#torontoChatPrompt").removeClass("hideChatbot"); $("#torontoChatHoverText").removeClass("hideChatbot"); // set the global data layer variable as true globalDataLayer.chatBotAccessed = true; }
}
function hideLoadingSpinner(){ //Hides the loading spinner console.log("SPINNER HIDDEN"); $(".chatBotLoadingIndicator").fadeOut(200); } function showLoadingSpinner(){ hideChatbotUnavailable(); //Shows the loading spinner console.log("SPINNER SHOWN"); $(".chatBotLoadingIndicator").fadeIn(500); } function showChatbotUnavailable(){ $(".chatBotUnavailable").show(); } function hideChatbotUnavailable(){ $(".chatBotUnavailable").hide(); } function closeChatWindow(){ $("#torontoChatPage").slideUp(100, function(){ $("#chatbotToronto").slideDown(300, onChatWindowCloseComplete()); }); // R182-70: reset checkTime flag and close the timer handleTorontoTimer("close"); } function onChatWindowOpenComplete(){ console.log("Chat Window is OPEN now!"); chatMinimized = false; $("#openChatForAccessibilityMessage").focus(); //56: check if accessed in mobile, make chat window full size if(isMobileDevice() || screen.width<750) { $("#torontoChatPage").css("width",screen.width+"px"); $("#torontoChatPage").css("height",screen.height+"px"); $("#torontoChatPage").css("left","0"); //$("#torontoChatPage").css("top","0");
}).fail(function(jqXHR, textStatus){ console.log("!!!!!!!!Refresh Token service failed!!!!!!!!!!!"); hideLoadingSpinner(); showChatbotUnavailable(); });
function setTokenBuffer(actualTokenExpiry){ var today = new Date(); var secsFromBegining = today.getTime(); var tokenExpiryWithBuffer = actualTokenExpiry - 120; //in seconds, also
keeping a buffer of 120 sec. var expirationTime = secsFromBegining + (tokenExpiryWithBuffer*1000); //milliseconds localStorage.expirationTimeWithBuffer = expirationTime; } function startPollingTokenExpiry(){ var pollingInterval = setInterval(function(){ if(checkForTokenExpiry(localStorage.expirationTimeWithBuffer)){ clearInterval(pollingInterval); localStorage.removeItem("expirationTimeWithBuffer"); refreshToken(); } },3000); } function checkForTokenExpiry(expirationTime){ var today = new Date(); var secsFromBegining = today.getTime(); if(secsFromBegining >= expirationTime){ //token expired return true; } else{ return false; } } window.addEventListener("message", receiveMessage, false); function receiveMessage(event){ if(chatBotUrl.indexOf(event.origin)>-1){ if(event.data == "botReplied"){ botReplied(); // R182-70: reset timer handleTorontoTimer("reset"); } else if(event.data == "botStartOver"){ botStartOver(); // R182-70: reset timer handleTorontoTimer("reset"); } console.log("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++"); console.log(event); console.log(JSON.stringify(event)); console.log("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++"); } } //BOT CALLBACKS, DO NOT CHANGE FUNCTION NAME! function botReplied(){ console.log("<==========================BOT REPLIED==========================>"); if(localStorage.torontoChatLaunched == "true" && chatMinimized && ! chatOpenedFirstTimeOnPage){
}); var openVideoModalId = ""; var eventHandlersAttached = false; $("html").on("click", ".videoContent", function(){ var targetId = $(this).children("a").data("target"); openVideoModalId = targetId.substring(1, targetId.length); }); var playlistMasterObject = {}; var accountId = parseInt($("#brightCoveAccountId").val()); //SSC controlled var playerId = $("#brightCovePlayerId").val(); //SSC controlled // function fetchPlaylist(playlistId, numberOfVideosPerPage){ function fetchPlaylist(playlistId, numberOfVideosPerPage){
playlistId = parseInt(playlistId); playlistMasterObject[playlistId] = {}; // var numberOfVideosPerPage = $("div[data-playlistid='"+playlistId+"']").data("perPage"); //Ajax call goes here $.ajax({ type: 'GET', url: "/hp-ppsservices/brightcove/accounts/"+accountId+"/playlists/"+playlistId+"/videos", contentType: "application/json", dataType: 'json' }).done(function(data){ // on success playlistMasterObject[playlistId].perPage = numberOfVideosPerPage; playlistMasterObject[playlistId].playlistId = playlistId; playlistMasterObject[playlistId].copyofjsonData = data; playlistManager(playlistId); }).fail(function(jqXHR, textStatus){ }); } function playlistManager(playlistId){ playlistId = parseInt(playlistId); var jsonData = playlistMasterObject[playlistId].copyofjsonData; var perPage = playlistMasterObject[playlistId].perPage; if(!eventHandlersAttached){ eventHandlersAttached = true; $('.prev').on('tap click', function(){ var playlistContext = $ (this).parents(".videoPlaylistWrapper").children(".videoPlaylist"); var playlistId = playlistContext.data("playlist-id"); var perPage = parseInt(playlistMasterObject[playlistId].perPage); var copyofjsonData = playlistMasterObject[playlistId].copyofjsonData; var curPage = parseInt(parseInt($ (this).parents(".containerForPaginationFoot").find(".paginationEndVal").text())/per Page); var remainder = parseInt($ (this).parents(".containerForPaginationFoot").find(".paginationEndVal").text()) %perPage; if(remainder > 0){ curPage = curPage + 1; } curPage--; response(copyofjsonData, "false", playlistContext, curPage); }); $('.showAll').on('tap click', function(){ var playlistWrapperContext = $ (this).parents(".videoPlaylistWrapper"); playlistWrapperContext.find('.showAll').hide(); playlistWrapperContext.find('.showLess').show(); playlistWrapperContext.find('.pagination-
less').attr('disabled','disabled'); playlistWrapperContext.find('.paginationless').addClass('disabled'); playlistWrapperContext.find('.paginationmore').attr('disabled','disabled'); playlistWrapperContext.find('.paginationmore').addClass('disabled'); var playlistContext = $ (this).parents(".videoPlaylistWrapper").children(".videoPlaylist"); var playlistId = playlistContext.data("playlist-id"); var perPage = parseInt(playlistMasterObject[playlistId].perPage); var copyofjsonData = playlistMasterObject[playlistId].copyofjsonData; var curPage = parseInt($ (this).parents(".paginationText").find(".paginationEndVal").text())/perPage; response(copyofjsonData, "true", playlistContext, curPage); }); $('.showLess').on('tap click', function(){ var playlistWrapperContext = $ (this).parents(".videoPlaylistWrapper"); playlistWrapperContext.find('.showAll').show(); playlistWrapperContext.find('.showLess').hide(); var playlistContext = $ (this).parents(".videoPlaylistWrapper").children(".videoPlaylist"); var playlistId = playlistContext.data("playlist-id"); var perPage = parseInt(playlistMasterObject[playlistId].perPage); var copyofjsonData = playlistMasterObject[playlistId].copyofjsonData; var curPage = parseInt($ (this).parents(".paginationText").find(".paginationEndVal").text())/perPage; response(copyofjsonData, "false", playlistContext, curPage); }); $('.next').on('tap click', function(){ var playlistContext = $ (this).parents(".videoPlaylistWrapper").children(".videoPlaylist"); var playlistId = playlistContext.data("playlist-id"); var perPage = parseInt(playlistMasterObject[playlistId].perPage); var copyofjsonData = playlistMasterObject[playlistId].copyofjsonData; var curPage = parseInt($ (this).parents(".containerForPaginationFoot").find(".paginationEndVal").text())/per Page; curPage++; response(copyofjsonData, "false", playlistContext, curPage); }); }
var perPage= playlistMasterObject[playlistId].perPage; // var curPage= 1; var copyofjsonData;
var modalGlobal = ""; for(var i = 0; i < jsonData.length; i++){ var title = jsonData[i].description; var videoId = jsonData[i].id; var videoName = jsonData[i].name; var videoDescription = jsonData[i].description; var videoPoster = jsonData[i].images.poster; modalGlobal = modalGlobal + '