
try{(function(){
var _1=false;
if(typeof wptheme==="undefined"||!wptheme){
wptheme={};
}
i$.mash(wptheme,{togglePageMode:function(){
return i$.modules.loadDeferred().then(function(){
var _2=i$.fromPath("com.ibm.mashups"),_3=_2?com.ibm.mashups.builder.model.Factory.getRuntimeModel():null,_4=_2?com.ibm.mashups.enabler.user.Factory.getUserModel():null,_5=document.getElementsByTagName("body")[0],_6=function(_7){
if(_2){
com.ibm.mashups.services.ServiceManager.getService("eventService").broadcastEvent("com.ibm.mashups.builder.changePageMode",_7);
_3.getCurrentPage().setPageMode(_7);
}
i$.fireEvent("wptheme/contextMenu/invalidate/all");
};
if((!_2&&!i$.hasClass(_5,"edit-mode"))||(_2&&_4.getAnonymousMode()!=com.ibm.mashups.enabler.user.AnonymousMode.ANONYMOUS&&_3.getCurrentPage().getPageMode()!="edit")){
_6("edit");
i$.addClass(_5,"edit-mode");
if(!_1){
if(!i$.isIE&&!i$.isOpera&&_2){
window.onbeforeunload=function(){
if(com.ibm.mashups.builder.model.Factory.getRuntimeModel().getCurrentPage().isDirty()){
return com.ibm.mm.builder.coreWidgetsStrings.I_PAGE_SAVE_WARNING;
}
};
}
_1=true;
}
}else{
_6("view");
i$.removeClass(_5,"edit-mode");
}
},function(_8){
console.log("Error going into edit mode. Most likely a session timeout. Refreshing. "+_8);
window.location.reload();
});
},mobileGoToSearch:function(id,_9,_a,_b,_c,_d,_e){
var _f=document.getElementById(_c);
var _10=document.getElementById("wpthemeSearchBoxInput");
if(i$.hasClass(_f,_9)){
wptheme.toggleMobileNav(id,_9,_a,_b,_c,_d,_e);
if(_10){
setTimeout(function(){
_10.focus();
},550);
}
}else{
if(_10){
_10.focus();
}
}
},mobileNavResizeBinding:null,mobileNavSideLastExpanded:[],mobileNavSideExpanded:[],mobileNavSideTogglingRoot:false,resizeMobileNavSide:function(e){
var _11=document.getElementsByTagName("header")[0];
var _12,id;
_12=document.getElementById("wpthemeNavRoot");
if(_12){
_12.style.top=_11.offsetHeight+"px";
_12.style.height=(window.innerHeight-_11.offsetHeight)+"px";
}
for(var i=0;i<wptheme.mobileNavSideExpanded.length;i++){
id=wptheme.mobileNavSideExpanded[i];
id=id.substr(0,id.length-4)+"Subnav";
_12=document.getElementById(id);
if(_12){
_12.style.top=_11.offsetHeight+"px";
_12.style.height=(window.innerHeight-_11.offsetHeight)+"px";
}
}
},animateMobileNavSidePanel:function(_13,_14,_15){
var _16=_13.offsetLeft;
if(ibmCfg.themeConfig.isRTL){
_16=parseInt(_13.style.right);
}
if(this.mobileNavSideTogglingRoot&&_14<_16){
_14=-_13.offsetWidth;
}
var _17=0;
var _18=Math.ceil(Math.abs(_14-_16)/5);
if(_16==_14){
_18=0;
}else{
if(_16>_14){
_18=-_18;
}
}
if(_18>0&&!this.mobileNavSideTogglingRoot){
if(ibmCfg.themeConfig.isRTL){
_13.style.clip="rect(0px,0px,"+_13.offsetHeight+"px,0px)";
}else{
_13.style.clip="rect(0px,"+_13.offsetWidth+"px,"+_13.offsetHeight+"px,"+_13.offsetWidth+"px)";
}
}
var _19=setInterval(function(){
if(_18>0&&_16+_18>_14){
_18=_14-_16;
}
if(_18<0&&_16+_18<_14){
_18=-(_16-_14);
}
if(_18<0&&!wptheme.mobileNavSideTogglingRoot){
if(ibmCfg.themeConfig.isRTL){
_13.style.clip="rect(0px,"+(_13.offsetWidth-(_17-=_18))+"px,"+_13.offsetHeight+"px,0px)";
}else{
_13.style.clip="rect(0px,"+_13.offsetWidth+"px,"+_13.offsetHeight+"px,"+(_17-=_18)+"px)";
}
}
if(_18>0&&!wptheme.mobileNavSideTogglingRoot){
if(ibmCfg.themeConfig.isRTL){
_13.style.clip="rect(0px,"+(_17+=_18)+"px,"+_13.offsetHeight+"px,0px)";
}else{
_13.style.clip="rect(0px,"+_13.offsetWidth+"px,"+_13.offsetHeight+"px,"+(_13.offsetWidth-(_17+=_18))+"px)";
}
}
if(ibmCfg.themeConfig.isRTL){
_13.style.right=(_16+=_18)+"px";
}else{
_13.style.left=(_16+=_18)+"px";
}
if(_18>0&&_16>=_14||_18<0&&_16<=_14||_18==0){
clearInterval(_19);
_13.style.clip="";
if(_15){
_15.call();
}
}
},1);
},toggleMobileNav:function(id,_1a,_1b,_1c,_1d,_1e,_1f){
var _20=document.getElementById(id);
var _21=document.getElementById("wpthemeNavRootLink");
var _22=document.getElementById(id+"Link");
var _23=document.getElementById(id+"Access");
var _24=document.getElementById(id+"Subnav");
var _25=document.getElementsByTagName("header")[0];
var _26=document.getElementById("layoutContainers");
if(_20){
if(_1f==0){
if(i$.hasClass(_21,"wpthemeNavOpened")){
i$.removeClass(_21,"wpthemeNavOpened");
}else{
i$.addClass(_21,"wpthemeNavOpened");
}
}
if(i$.hasClass(_20,_1a)){
if(id==_1d&&_1e){
this.mobileNavSideTogglingRoot=true;
_20.style.top=_25.offsetHeight+"px";
_20.style.height=(window.innerHeight-_20.offsetTop)+"px";
if(ibmCfg.themeConfig.isRTL){
_20.style.right=(-_20.offsetWidth)+"px";
}else{
_20.style.left=(-_20.offsetWidth)+"px";
}
this.mobileNavResizeBinding=i$.bindDomEvt(window,"resize",this.resizeMobileNavSide);
}
i$.removeClass(_20,_1a);
_20.setAttribute("aria-expanded","true");
_22.setAttribute("aria-label",_1c);
_22.title=_23.innerHTML=_1c;
if(id==_1d&&_1e){
_25.style.position="fixed";
_25.style.width="100%";
_26.style.paddingTop=_25.offsetHeight+10+"px";
_25.style.zIndex="9998";
_25.style.top="0px";
this.animateMobileNavSidePanel(_20,0,function(){
if(wptheme.mobileNavSideLastExpanded.length==0){
wptheme.mobileNavSideTogglingRoot=false;
}
});
}
if(_1e){
if(id==_1d){
for(var i=0;i<this.mobileNavSideLastExpanded.length;i++){
document.getElementById(this.mobileNavSideLastExpanded[i]).onclick.call();
}
}else{
this.mobileNavSideExpanded.push(id+"Link");
_22.parentNode.parentNode.parentNode.onclick=_22.onclick;
}
}
if(_24&&_1e){
var _27=document.getElementById(_1d);
var _28=_27.parentNode;
if(_24.parentNode!=_28){
_24=_24.parentNode.removeChild(_24);
_28.appendChild(_24);
}
var _29=Math.min((_1f*70),Math.floor(window.innerWidth-_24.offsetWidth)-1);
_24.style.top=_27.offsetTop+"px";
_24.style.height=(window.innerHeight-_24.offsetTop)+"px";
if(this.mobileNavSideTogglingRoot){
if(ibmCfg.themeConfig.isRTL){
_24.style.right=(-_24.offsetWidth)+"px";
}else{
_24.style.left=(-_24.offsetWidth)+"px";
}
}else{
if(ibmCfg.themeConfig.isRTL){
_24.style.right=(_29-_24.offsetWidth)+"px";
}else{
_24.style.left=(_29-_24.offsetWidth)+"px";
}
}
i$.removeClass(_24,_1a);
this.animateMobileNavSidePanel(_24,_29,function(){
if(wptheme.mobileNavSideTogglingRoot&&id+"Link"==wptheme.mobileNavSideLastExpanded[wptheme.mobileNavSideLastExpanded.length-1]){
wptheme.mobileNavSideTogglingRoot=false;
}
});
}
}else{
if(_1e){
if(id==_1d){
this.mobileNavSideTogglingRoot=true;
this.mobileNavSideLastExpanded=this.mobileNavSideExpanded.slice(0);
for(var i=this.mobileNavSideExpanded.length-1;i>=0;i--){
document.getElementById(this.mobileNavSideExpanded[i]).onclick.call();
}
}else{
var _2a=id+"Link";
var i=-1;
for(var j=this.mobileNavSideExpanded.length-1;j>=0;j--){
if(this.mobileNavSideExpanded[j]==_2a){
i=j;
break;
}
}
if(i!=-1){
var _2b;
for(var j=this.mobileNavSideExpanded.length-1;j>=i;j--){
_2b=this.mobileNavSideExpanded.pop();
if(_2a!=_2b){
document.getElementById(_2b).onclick.call();
}
}
}
_22.parentNode.parentNode.parentNode.onclick=null;
}
}
if(_24&&_1e){
var _29=_24.offsetLeft;
if(ibmCfg.themeConfig.isRTL){
_29=parseInt(_24.style.right);
}
this.animateMobileNavSidePanel(_24,_29-_24.offsetWidth,function(){
i$.addClass(_24,_1a);
if(_24.parentNode!=_20){
_24=_24.parentNode.removeChild(_24);
_20.appendChild(_24);
}
});
}
if(id==_1d&&_1e){
_25.style.position="static";
_26.style.paddingTop="";
_25.style.width="auto";
_25.style.zIndex="auto";
this.animateMobileNavSidePanel(_20,-_20.offsetWidth,function(){
i$.addClass(_20,_1a);
_20.setAttribute("aria-expanded","false");
_22.setAttribute("aria-label",_1b);
_22.title=_23.innerHTML=_1b;
wptheme.mobileNavSideTogglingRoot=false;
});
i$.unbindDomEvt(this.mobileNavResizeBinding);
this.mobileNavResizeBinding=null;
}else{
i$.addClass(_20,_1a);
_20.setAttribute("aria-expanded","false");
_22.setAttribute("aria-label",_1b);
_22.title=_23.innerHTML=_1b;
}
}
}
},toggleMobileTopNav:function(_2c,_2d){
var _2e=document.getElementById("wpthemeTopNavToggleBtn");
var _2f=document.getElementById("wpthemeTopNavToggleBtnAccess");
var _30=document.getElementsByTagName("header")[0];
var _31=_30.children[0];
if(i$.hasClass(_2e,"wpthemeTopNavOpened")){
_31.style.display="none";
i$.removeClass(_2e,"wpthemeTopNavOpened");
_2e.setAttribute("aria-label",_2c);
_2e.title=_2f.innerHTML=_2c;
}else{
_31.style.display="block";
i$.addClass(_2e,"wpthemeTopNavOpened");
_2e.setAttribute("aria-label",_2d);
_2e.title=_2f.innerHTML=_2d;
}
this.resizeMobileNavSide();
}});
var _32=document.getElementById("wpthemeHelpLink");
var _33=document.getElementById("wpthemeHelpOnClick");
var _34=document.getElementById("wpthemeHelpAnchor");
if(!(_32===null&&_33===null)&&_34!=null){
if(_32!=null){
var _35=_32.innerHTML;
_34.onclick=function(){
window.open(_35,"wpthemeHelp","width=800,height=600");
};
}else{
if(_33!=null){
var _36=_33.innerHTML;
_34.onclick=function(){
eval(_36);
};
}
}
}
})();


}catch(e){console.log("Module 'wp_theme_edit': ",e);}
try{// create a test node off the browser screen to calculate high contrast mode
var testNode = document.createElement("div");
testNode.className = "highContrastTestNode";
document.body.appendChild(testNode);
// look at the computed style for the test node
var styles = null;
try {
	styles = document.defaultView.getComputedStyle(testNode, "");
} catch(e) {
	styles = testNode.currentStyle;
}
var testImg = styles.backgroundImage;
if ((styles.borderTopColor == styles.borderRightColor) || (testImg != null && (testImg == "none" || testImg == "url(invalid-url:)" ))) {
	document.getElementsByTagName("body")[0].className+=" lotusImagesOff";
}
document.body.removeChild(testNode);

}catch(e){console.log("Module 'wp_one_ui_30': ",e);}
try{(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);
}
}
}
}
});
}
})();


}catch(e){console.log("Module 'wp_theme_skin_region': ",e);}
try{(function(){
    i$.merge({
	"WARNING_0":"Warning",
	"DELETE_0":"Delete",
	"INFO_0":"Information",
	"MESSAGES_AVAILABLE_1":"${0} messages are available for review",
	"SHOW_DETAILS_0":"Show Details",
	"ERROR_0":"Error",
	"HIDE_DETAILS_0":"Hide Details"
},i$.fromPath("wptheme.statusBar.nls",true));
})();
}catch(e){console.log("Module 'wp_status_bar': ",e);}
try{(function(){
if(typeof com==="undefined"||!com){
com={};
}
if(typeof com.ibm==="undefined"||!com.ibm){
com.ibm={};
}
if(typeof com.ibm.widgets==="undefined"||!com.ibm.widgets){
com.ibm.widgets={};
}
if(typeof com.ibm.widgets.StatusType==="undefined"||!com.ibm.widgets.StatusType){
com.ibm.widgets.StatusType=function(id,_1,_2,_3){
this._id=id;
this._styleClass=_1;
this._iconPath=_2;
this._iconAlt=_3;
};
}
if(typeof com.ibm.widgets.StatusMessage==="undefined"||!com.ibm.widgets.StatusMessage){
com.ibm.widgets.StatusMessage=function(_4,_5,_6){
this._type=_4;
this._message=_5;
if(!i$.isString(_5)&&_5.message&&i$.isString(_5.message)){
this._message=_5.message;
}
this._details=_6;
};
}
if(typeof com.ibm.widgets.StatusBarV2==="undefined"||!com.ibm.widgets.StatusBarV2){
com.ibm.widgets.StatusBarV2=function(_7){
this.uid=_7;
this.showDetails=false;
this._messages=[];
this._connections=[];
this._numMessages=0;
this._baseURL=window.location.protocol+"//"+window.location.host;
this.blankGifIcon="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";
this._statusTypesMap={"error":new com.ibm.widgets.StatusType(0,"wpthemeError",this.blankGifIcon,wptheme.statusBar.nls.ERROR_0),"warning":new com.ibm.widgets.StatusType(1,"wpthemeWarning",this.blankGifIcon,wptheme.statusBar.nls.WARNING_0),"info":new com.ibm.widgets.StatusType(2,"wpthemeInfo",this.blankGifIcon,wptheme.statusBar.nls.INFO_0)};
i$.addListener("/portal/status",i$.scope(this,this.addMessage));
i$.addListener("/message/status",i$.scope(this,this.addMessage));
i$.addListener("/portal/status/clear",i$.scope(this,this.clearMessage));
i$.addListener("/message/status/clear",i$.scope(this,this.clearMessage));
if(typeof (ibmCfg)!="undefined"&&ibmCfg.portalConfig){
this.isBidi=ibmCfg.portalConfig.isRTL;
}else{
if(typeof (ibmPortalConfig)!="undefined"){
this.isBidi=ibmPortalConfig.isRTL;
}else{
if(typeof (ibmConfig)!="undefined"){
this.isBidi=ibmConfig.isBidi;
}
}
}
i$.addOnUnload(i$.scope(this,this._onWindowUnload));
this.containerNode=i$.byId("wpthemeStatusBarContainer");
};
}
i$.augment(com.ibm.widgets.StatusBarV2,{_onWindowUnload:function(){
i$.forEach(this._connections,function(_8){
i$.unbindDomEvt(_8);
});
this._connections=null;
this.clear();
this._messages=null;
},_getStatusContainer:function(){
return this.containerNode;
},_escapeHTML:function(_9){
if(_9.replace){
return _9.replace(/&/g,"&amp;").replace(/>/g,"&gt;").replace(/</g,"&lt;").replace(/"/g,"&quot;");
}
return _9;
},setShowDetails:function(_a){
this.showDetails=_a;
},toggleShowDetails:function(){
this.setShowDetails(!this.showDetails);
this.render();
},clear:function(){
var _b=this._getStatusContainer();
if(!!_b){
_b.innerHTML="";
_b.setAttribute("role","");
_b.setAttribute("wairole","");
}
this._messages.length=0;
},clearMessage:function(_c){
if(_c.uid&&_c.uid!=this.uid){
return;
}
var _d=_c.message;
if(typeof _d==="undefined"||_d===null){
this.clear();
}else{
for(var i=this._messages.length-1;i>=0;i--){
if(this._messages[i]._type==_d._type&&this._messages[i]._message==_d._message&&this._messages[i]._details==_d._details){
this._messages.splice(i,1);
}
}
if(this._messages.length==0){
this.clear();
}else{
if(this._messages.length<100){
this.render(this._getStatusContainer());
}
}
}
},addMessage:function(_e){
if(_e.uid&&_e.uid!=this.uid){
return;
}
var _f=_e.message;
this._messages.push(_f);
if(this._messages.length<100){
this.render(this._getStatusContainer());
}
},render:function(_10){
if(_10==null){
_10=this._getStatusContainer();
}
_10.innerHTML="";
if(this._messages.length>1){
this.renderHeader(_10);
}else{
if(this._messages.length==1){
this.renderMessage(_10,this._messages[0],this.showDetails,0);
}
}
if(this.showDetails&&this._messages.length>1){
for(x in this._messages){
this.renderMessage(_10,this._messages[x],this.showDetails,x);
}
}
},renderHeader:function(_11){
if(this._messages.length>1){
var _12=2;
for(var i=0;i<this._messages.length;i++){
_12=Math.min(_12,this._statusTypesMap[this._messages[i]._type]._id);
}
var _13="info";
for(x in this._statusTypesMap){
if(this._statusTypesMap[x]._id==_12){
_13=x;
break;
}
}
var _14=new com.ibm.widgets.StatusMessage(_13,wptheme.statusBar.nls.MESSAGES_AVAILABLE_1.replace("${0}",this._messages.length),"");
this.renderMessage(_11,_14,this.showDetails,-1);
}
},renderMessage:function(_15,_16,_17,_18){
var _19=this._statusTypesMap[_16._type];
var _1a=document.createElement("div");
_1a.className="wpthemeMessage "+_19._styleClass;
if(this._messages.length>1&&_18>=0){
_1a.className+=" wpthemeMoreMsg";
}
var _1b=document.createElement("img");
_1b.className="wpthemeMsgIcon "+(_19._styleClass=="wpthemeError"?"wpthemeMsgIconError":_19._styleClass=="wpthemeWarning"?"wpthemeMsgIconWarning":"wpthemeMsgIconInfo");
_1b.src=_19._iconPath;
_1b.alt=_1b.title=_19._iconAlt;
_1a.appendChild(_1b);
var _1c=document.createElement("span");
_1c.className="wpthemeAltText";
_1c.innerHTML=this._escapeHTML(_19._iconAlt+":");
_1a.appendChild(_1c);
var _1d=document.createElement("div");
_1d.className="wpthemeMessageBody";
_1d.innerHTML=this._escapeHTML(_16._message);
_1a.appendChild(_1d);
if((this._messages.length>1&&_18<0)||(this._messages.length==1)){
if(_16._details&&_16._details.length>0||_18<0){
var _1e=document.createElement("a");
_1e.href="javascript:void(0)";
_1e.className="wpthemeHideShow";
_1e.role="button";
this._connections.push(i$.bindDomEvt(_1e,"onclick",i$.scope(this,this.toggleShowDetails)));
var _1f=document.createElement("img");
_1f.className="wpthemeMsgIcon16";
_1f.src=ibmCfg.themeConfig.modulesWebAppBaseURI+"/themes/html/dynamicSpots/icons/blank.gif";
_1e.appendChild(_1f);
var _20=document.createElement("span");
_20.className="wpthemeAltText";
_1e.appendChild(_20);
}else{
_17=false;
}
var _21=document.createElement("a");
_21.href="javascript:void(0);";
_21.className="wpthemeDelete";
_21.role="button";
_21.title=wptheme.statusBar.nls.DELETE_0;
this._connections.push(i$.bindDomEvt(_21,"onclick",i$.scope(this,this.clear)));
var _22=document.createElement("img");
_22.alt=wptheme.statusBar.nls.DELETE_0;
_22.src=ibmCfg.themeConfig.modulesWebAppBaseURI+"/themes/html/dynamicSpots/icons/blank.gif";
_21.appendChild(_22);
var _23=document.createElement("span");
_23.className="wpthemeAltText";
_23.innerHTML=this._escapeHTML(wptheme.statusBar.nls.DELETE_0);
_21.appendChild(_23);
if(_16._details&&_16._details.length>0||_18<0){
if(_17){
_1e.title=wptheme.statusBar.nls.HIDE_DETAILS_0;
_1f.className+=" wpthemeMsgIconHide";
_1f.alt=wptheme.statusBar.nls.HIDE_DETAILS_0;
_20.innerHTML=this._escapeHTML(wptheme.statusBar.nls.HIDE_DETAILS_0);
}else{
_1e.title=wptheme.statusBar.nls.SHOW_DETAILS_0;
_1f.className+=" wpthemeMsgIconShow";
_1f.alt=wptheme.statusBar.nls.SHOW_DETAILS_0;
_20.innerHTML=this._escapeHTML(wptheme.statusBar.nls.SHOW_DETAILS_0);
}
_1a.appendChild(_1e);
}
_1a.appendChild(_21);
}
var _24=document.createElement("div");
_24.className="wpthemeClear";
_1a.appendChild(_24);
if(_16._details&&_16._details.length>0&&_17&&_18>=0){
var _25=document.createElement("div");
_25.className="wpthemeDetails";
_25.appendChild(document.createTextNode(_16._details));
_1a.appendChild(_25);
}
_15.appendChild(_1a);
_15.setAttribute("role","alert");
_15.setAttribute("wairole","alert");
}});
if(typeof wpstatusbar==="undefined"||!wpstatusbar){
wpstatusbar=new com.ibm.widgets.StatusBarV2("ibmStatusBox");
}
var _26=i$.getCookie("ibm.portal.operations.error");
if(_26){
var _27=i$.fromJson(decodeURIComponent(_26));
var _28="error";
if(_27.errorType){
_28=_27.errorType;
}else{
if(_27.errorCode){
if(_27.errorCode=="400"){
_28="error";
}
}
}
i$.fireEvent("/portal/status",[{message:new com.ibm.widgets.StatusMessage(_28,_27.errorMessage?_27.errorMessage:"",_27.errorDetails?_27.errorDetails:""),uid:"ibmStatusBox"}]);
i$.deleteCookie("ibm.portal.operations.error");
}
i$.addOnLoad(function(){
if("localStorage" in window&&window["localStorage"]!==null){
if(localStorage["com.ibm.wp.toolbar.msg.msg"]!=null){
i$.fireEvent("/message/status",[{message:new com.ibm.widgets.StatusMessage(localStorage["com.ibm.wp.toolbar.msg.type"],localStorage["com.ibm.wp.toolbar.msg.msg"],""),uid:"ibmStatusBox"}]);
localStorage.removeItem("com.ibm.wp.toolbar.msg.type");
localStorage.removeItem("com.ibm.wp.toolbar.msg.msg");
}
}
});
})();


}catch(e){console.log("Module 'wp_status_bar': ",e);}
try{(function(){
var _1=ibmCfg.portalConfig.contentHandlerURI+((ibmCfg.portalConfig.contentHandlerURI.indexOf("?")<0)?"?":"&")+"uri=menu:${id}";
var _2=false;
var _3=function(){
return i$.hasClass(document.getElementsByTagName("body")[0],"edit-mode");
};
if(typeof wptheme==="undefined"||!wptheme){
wptheme={};
}
i$.mash(wptheme,{getWindowIDFromSkin:function(_4){
while((_4=_4.parentNode)!=null){
if(i$.hasClass(_4,"component-control")){
var m=_4&&(_4.className||"").match(/id-([\S]+)/);
return m&&m[1];
}
}
return null;
},getPortletState:function(_5){
var _6=i$.byId("portletState");
if(_6){
if(!_6._cache){
_6._cache=i$.fromJson(_6.innerHTML);
_6._cache._defaults={"windowState":"normal","portletMode":"view"};
}
if(_6._cache[_5]){
return _6._cache[_5];
}else{
return _6._cache._defaults;
}
}
return {};
},isValidOp:function(_7){
if(_7.visibility===false){
return false;
}
var _8=_7.metadata||{};
switch(_7.id){
case "ibm.portal.operations.changePortletMode":
return wptheme.getPortletState(_8.wid).portletMode!=_8.portletMode;
case "ibm.portal.operations.changeWindowState":
return wptheme.getPortletState(_8.wid).windowState!=_8.windowState;
default:
}
return true;
},operation:{changeToHelpMode:function(_9){
var _a=window.location.href;
if(_9.actionUrl){
if(_9.actionUrl.indexOf("?")==0){
var _b=_a.indexOf("#");
if(_b!=-1){
var _c=_a.substring(0,_b);
var _d=_a.substring(_b);
_a=_c+(_c.indexOf("?")==-1?"?":"&")+_9.actionUrl.substring(1);
_a+=_d;
}else{
_a+=(_a.indexOf("?")==-1?"?":"&")+_9.actionUrl.substring(1);
}
}else{
_a=_9.actionUrl;
}
}
window.open(_a,"","resizable=yes,scrollbars=yes,menubar=no,toolbar=no,status=no,width=800,height=600,screenX=10,screenY=10,top=10,left=10");
}},canImpersonate:function(){
return ibmCfg.portalConfig.canImpersonate;
},contextMenu:{cache:{},css:{focus:"wpthemeMenuFocus",disabled:"wpthemeMenuDisabled",show:"wpthemeMenuShow",error:"wpthemeMenuError",menuTemplate:"wpthemeTemplateMenu",submenuTemplate:"wpthemeTemplateSubmenu",loadingTemplate:"wpthemeTemplateLoading"},init:function(_e,_f,_10){
_e._contextMenu=_e._contextMenu||{};
_e._contextMenu.id=_e._contextMenu.id||Math.round(Math.random()*1000000000);
_e.setAttribute("id",_e._contextMenu.id);
_e._contextMenu.menuId=_f;
_e._contextMenu.jsonQuery=_10;
var _11=_e._contextMenu;
var _12=function(_13){
if(_13.displayMenu){
i$.fireEvent("wptheme/contextMenu/close/all");
if(!_11._submenu){
i$.fireEvent("wptheme/contextMenu/close/all");
wptheme.contextMenu._updateAbsolutePosition(i$.byId(_11.id));
}
var _14=wptheme.contextMenu._adjustScreenPositionStart();
i$.addClass((_11.shadowNode)?_11.shadowNode:i$.byId(_11.id),wptheme.contextMenu.css.show);
wptheme.contextMenu._adjustScreenPositionEnd(_14);
var _15=i$.byId(_11.id)._firstSelectable;
if(_15){
_15.focus();
i$.byId(_11.id)._currentSelected=_15;
}
i$.addListener("wptheme/contextMenu/close/all",function(){
var _16=i$.byId(_11.id);
});
}
};
wptheme.contextMenu._initialize(_e).then(_12,_12);
_e=null;
},initSubmenu:function(_17,_18,_19){
_17._contextMenu=_17._contextMenu||{};
_17._contextMenu._submenu=true;
_17._contextMenu._menuitemTemplate=_19._menuitemTemplate;
_17._contextMenu._subMenuTemplate=_19._subMenuTemplate;
_17._contextMenu._loadingTemplate=_19._loadingTemplate;
wptheme.contextMenu.init(_17,_18,_19.jsonQuery);
},_findFocusNode:function(_1a){
var _1b,i,_1c;
var _1d=function(_1e,_1f){
var l=_1e.childNodes.length;
for(i=0;i<l;i++){
if(_1b){
break;
}
_1c=_1e.childNodes[i];
if(i$.hasClass(_1c,wptheme.contextMenu.css.focus)){
_1b=_1c;
break;
}
if(_1c.childNodes){
i=_1d(_1c,i);
}
}
return _1f;
};
if(i$.hasClass(_1a,wptheme.contextMenu.css.focus)){
return _1a;
}
_1d(_1a);
return _1b;
},_findNodes:function(_20){
var _21,_22,_23,i,_24;
var _25=function(_26,_27){
for(i=_26.childNodes.length-1;i>=0;i--){
_24=_26.childNodes[i];
if(i$.hasClass(_24,wptheme.contextMenu.css.menuTemplate)){
_21=_24;
continue;
}
if(i$.hasClass(_24,wptheme.contextMenu.css.submenuTemplate)){
_22=_24;
continue;
}
if(i$.hasClass(_24,wptheme.contextMenu.css.loadingTemplate)){
_23=_24;
continue;
}
if(_24.childNodes){
i=_25(_24,i);
}
}
return _27;
};
_25(_20);
return {"menu":_21,"submenu":_22,"loading":_23};
},_invalidateCallback:function(){
wptheme.contextMenu.cache={};
},_initialize:function(_28){
var _29=true;
var _2a=_28._contextMenu;
if(wptheme.contextMenu.cache[_2a.id]||_2a._inProgress){
return i$.promise.resolved({displayMenu:_29});
}
_2a._inProgress=true;
i$.addListener("wptheme/contextMenu/invalidate/all",wptheme.contextMenu._invalidateCallback);
var _2b,_2c,tmp=i$.createDom("div");
if(_2a._submenu){
tmp.innerHTML=_2a._subMenuTemplate.replace(/\$\{submenu-id\}/g,_2a.id+"_menu");
_28.appendChild(tmp.firstChild);
_2b=i$.byId(_2a.id+"_menu");
_2c=i$.createDom("div");
_2c.innerHTML=_2a._loadingTemplate;
}else{
var _2d=wptheme.contextMenu._findNodes((_2a.shadowNode)?_2a.shadowNode:_28);
_2b=_2d.menu;
if(!_2a._menuitemTemplate){
_2a._menuitemTemplate=i$.trim(_2b.innerHTML);
}
if(!_2a._loadingTemplate){
_2c=i$.createDom("div");
_2c.appendChild(_2d.loading);
_2a._loadingTemplate=i$.trim(_2c.innerHTML);
_2c=null;
}
_2c=i$.createDom("div");
_2c.innerHTML=_2a._loadingTemplate;
tmp.appendChild(_2d.submenu.cloneNode(true));
if(!_2a._subMenuTemplate){
_2a._subMenuTemplate=i$.trim(tmp.innerHTML);
}
}
while(_2b.firstChild){
_2b.removeChild(_2b.firstChild);
}
_2b.appendChild(_2c);
var _2e;
if(_2a._submenu){
_2e=_2a.shadowNode;
}else{
if(_2a.shadowNode){
_2e=_2a.shadowNode;
}else{
_2e=wptheme.contextMenu._transformIntoAbsolutePosition(_28);
}
}
i$.addClass((_2e)?_2e:_28,wptheme.contextMenu.css.show);
i$.bindDomEvt((_2e)?_2e:_28,"onmouseleave",function(){
if(_2a._inProgress){
_29=false;
}
var _2f=i$.byId(_2a.id);
i$.removeClass((_2a.shadowNode)?_2a.shadowNode:_2f,wptheme.contextMenu.css.show);
if(!_2a.activeAction){
var _30=_2f._currentSelected;
if(_30){
_30.blur();
}
var _31=wptheme.contextMenu._findFocusNode(_2f);
((_31)?_31:_2f).focus();
}
});
return wptheme.contextMenu._load(_2a).then(function(_32){
var _33=wptheme.contextMenu._parseData(_32).then(function(_34){
_34=wptheme.contextMenu._filterMenu(_34);
if(!_34||_34.length==0){
var tmp=i$.createDom("div");
tmp.innerHTML=wptheme.contextMenu._fromTemplate(_2a._menuitemTemplate,wptheme.contextMenu.css.error,wptheme.contextMenu.nls.NO_ITEMS_0);
while(_2b.firstChild){
_2b.removeChild(_2b.firstChild);
}
_2b.appendChild(tmp);
}else{
wptheme.contextMenu._buildMenu(_2a,_2b,_34);
}
_2a._inProgress=false;
wptheme.contextMenu.cache[_2a.id]=true;
return {displayMenu:_29};
});
return _33;
},function(){
var tmp=i$.createDom("div");
tmp.innerHTML=wptheme.contextMenu._fromTemplate(_2a._menuitemTemplate,wptheme.contextMenu.css.error,wptheme.contextMenu.nls.ERROR_LOADING_0);
while(_2b.firstChild){
_2b.removeChild(_2b.firstChild);
}
_2b.appendChild(tmp);
_2a._inProgress=false;
wptheme.contextMenu.cache[_2a.id]=true;
return {displayMenu:_29};
});
},_load:function(_35){
var _36=_1.replace(/\$\{id\}/g,_35.menuId);
if(_35.jsonQuery){
_36+=(_36.indexOf("?")==-1?"?":"&")+i$.toQuery(_35.jsonQuery);
}
return i$.xhrGet({url:_36,headers:{"X-IBM-XHR":"true"},responseType:"json"}).then(function(_37){
return _37.data;
},function(_38){
var _39=_38.xhr.getResponseHeader("Content-Type")||"";
if((_39.indexOf("text/html")==0)||(_38.xhr.status==401)){
window.setTimeout(function(){
document.location.reload();
},0);
}
console.log("Error trying to load the context menu feed for '"+_35.menuId+"': "+_38);
return null;
});
},_parseData:function(_3a){
var _3b=[];
i$.each(_3a,function(_3c){
var _3d=i$.fromPath("moduleInfo.deferred",false,_3c)?i$.modules.loadDeferred():i$.promise.resolved(true);
_3b.push(_3d.then(function(){
var _3e=wptheme.contextMenu._checkFunction(_3c,_3c.visibilityFn,_3c,(typeof _3c.visibility!="undefined")?_3c.visibility:true);
var _3f=wptheme.contextMenu._checkFunction(_3c,_3c.enableFn,_3c,(typeof _3c.enabled!="undefined")?_3c.enabled:true);
return i$.whenAll(_3e,_3f).then(function(_40){
_3c._visible=_40[0];
_3c._enabled=_40[1];
return _3c;
});
}));
});
return i$.whenAll.apply(i$,_3b);
},_filterMenu:function(_41){
var _42=[],_43,_44={"type":"Separator"};
for(var i=_41.length-1;i>=0;i--){
_43=_41[i];
if(!_43._visible){
continue;
}
if(_43.type=="Separator"){
if(_44.type=="Separator"){
continue;
}
}else{
if(_43.type=="Header"){
if((_44.type=="Separator")||(_44.type=="Header")){
continue;
}
}
}
_44=_43;
_42.unshift(_43);
}
while(_42.length>0&&_42[0].type=="Separator"){
_42=_42.slice(1);
}
return _42;
},_buildMenu:function(_45,_46,_47){
var _48=document.createDocumentFragment(),tmp=i$.createDom("div"),_49,_4a,_4b,_4c;
for(var i=0,l=_47.length;i<l;i++){
_49=_47[i];
tmp.innerHTML=wptheme.contextMenu._fromTemplate(_45._menuitemTemplate,_49);
while(_4a=tmp.firstChild){
if(_4a.nodeType==1){
if(_49.type=="Submenu"){
_4a._menuitem=_49;
_4a._jsonData=_45;
i$.bindDomEvt(_4a,"onmouseover",wptheme.contextMenu._applySubmenu);
}else{
if(_49._enabled){
_4a.links={previous:_4b,next:null,sub:null};
if(_4b){
_4b.links.next=_4a;
}
if(!_4c&&_49.type!="Header"){
_4c=_4a;
}
_4a._menuitem=_49;
_4b=_4a;
i$.bindDomEvt(_4a,"onclick",function(evt){
wptheme.contextMenu._stopEventPropagation(evt);
wptheme.contextMenu._applyAction(evt);
setTimeout(function(){
var _4d=i$.byId(_45.id);
i$.removeClass((_45.shadowNode)?_45.shadowNode:_4d,wptheme.contextMenu.css.show);
},0);
});
i$.bindDomEvt(_4a,"onkeydown",function(evt){
return wptheme.contextMenu._applyKeyAction(evt);
});
i$.bindDomEvt(_4a,"onmouseover",function(evt){
return wptheme.contextMenu._applyFocusAction(evt);
});
}
}
if((_49.title)&&(i$.isRTL(_49.title.lang))){
i$.addClass(_4a,"rtl");
_4a.setAttribute("dir","RTL");
}
if(_49.markupId){
_4a.setAttribute("id",_49.markupId);
}
}
_48.appendChild(_4a);
}
}
while(_46.firstChild){
_46.removeChild(_46.firstChild);
}
_46.appendChild(_48);
i$.byId(_45.id)._firstSelectable=_4c;
i$.byId(_45.id)._currentSelected=null;
},_fromTemplate:function(_4e,_4f,_50){
var _51,_52,_53;
if(typeof (_4f)=="string"){
_51=_4f;
_52=_50;
_53="";
}else{
_51="type"+_4f.type;
if(_4f.itemClass){
_51+=" "+_4f.itemClass;
}
if(!_4f._enabled){
_51+=" "+wptheme.contextMenu.css.disabled;
}
_52=(_4f.title)?_4f.title.value:"";
_53=((_4f.description)?_4f.description.value:"");
}
return _4e.replace(/\$\{title\}/g,_52).replace(/"\$\{css-class\}"/g,"\""+(_51)+"\"").replace(/\$\{css-class\}/g,"\""+(_51)+"\"").replace(/"\$\{description\}"/g,"\""+_53+"\"").replace(/\$\{description\}/g,"\""+_53+"\"");
},_checkFunction:function(_54,fn,arg,_55){
if(fn){
if(!_54.fromPath){
_54.fromPath={};
}
var _56=_54.fromPath[fn]||i$.fromPath(fn);
_54.fromPath[fn]=_56;
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-method-override","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];
}
}}});
})();


}catch(e){console.log("Module 'wp_theme_menus': ",e);}
try{(function(){
    i$.merge({
	"NO_ITEMS_0":"No items to display",
	"ERROR_LOADING_0":"Error happened while loading the menu."
},i$.fromPath("wptheme.contextMenu.nls",true));
})();

}catch(e){console.log("Module 'wp_theme_menus': ",e);}
try{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="<ul><li>  "+$('#ID_pps_lbl_DetectMyDevice_ChromeStep1').val()+"</li><li>"+$('#ID_pps_lbl_DetectMyDevice_ChromeStep2').val()+"</li><li>"+$('#ID_pps_lbl_DetectMyDevice_ChromeStep3').val()+"</li></ul>";
        }
        // 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="<ul><li>  "+$('#ID_pps_lbl_DetectMyDevice_IE8Step1').val()+"</li><li>"+$('#ID_pps_lbl_DetectMyDevice_IE8Step2').val()+"</li><li>"+$('#ID_pps_lbl_DetectMyDevice_IE8Step3').val()+"</li></ul>";
	        	}
	         
	         else{
	        	 document.getElementById("showContent").innerHTML="<ul><li>  "+$('#ID_pps_lbl_DetectMyDevice_IEStep1').val()+"</li><li>"+$('#ID_pps_lbl_DetectMyDevice_IEStep2').val()+"</li></ul>";
	         }

        }
        // In Firefox
        else if ((objOffsetVersion=objAgent.indexOf("Firefox"))!=-1) {
         objbrowserName = "Firefox";
         document.getElementById("showContent").innerHTML="<ul><li>"+$('#ID_pps_lbl_DetectMyDevice_FirefoxStep1').val()+"</li><li>"+$('#ID_pps_lbl_DetectMyDevice_FirefoxStep2').val()+" <p><img src=\"https://h20614.www2.hp.com/ediags/gmd/Content/images/firefox-download-instruction-step.png\" width=\"84\" height=\"58\"></p></li><li>"+$('#ID_pps_lbl_DetectMyDevice_FirefoxStep3').val()+"</li><li>"+$('#ID_pps_lbl_DetectMyDevice_FirefoxStep4').val()+"</li></ul>";
        }
        // 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);
        }
        
    }
       
		});
       
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{/* 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 != "oneboxtextsearch") {
            $('.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(".search-bg").find(".clear-search");
                if($(clearIcon).length > 0 ){
                    $(clearIcon).focus();
                    }
            }*/

            else if ((event.which == KEY.UP)) {
                event.stopPropagation();
                event.preventDefault();
                $("." + typeAheadObjClass + " li a").last().focus();
                $("." + typeAheadObjClass + " li a").removeClass("hover");
                $("." + typeAheadObjClass + " li a").last().addClass("hover");
                (reqTypeaheadBox).val($(document.activeElement).text());
                // $(".typeAheadBox").val($(document.activeElement).text());
            }
        }
            /*
            else{
            if(event.which == KEY.TAB){
                var clearIcon = (reqTypeaheadBox).parents(".search-bg").find(".clear-search");
                if($(clearIcon).length > 0 ){
                    $(clearIcon).focus();
                    }
                }
            }*/
         if ((event.which == KEY.ENTER)) {

             event.preventDefault();
             (reqTypeaheadBox).val("");
             $("." + typeAheadObjClass).remove();
     }

    });

    // handle blur on typeahead box
     $(reqTypeaheadBox).on("blurTypeahead", function(event) {
            isHidePrediction(typeAheadObjClass, reqTypeaheadBox);
        });
     $(document).on("blur","." + typeAheadObjClass + " li a", function(event) {

            isHidePrediction(typeAheadObjClass, reqTypeaheadBox);
        });



     // 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
         		return;
         	}
     	    }
            (reqTypeaheadBox).data("productid",$(this).data("productid"));
            $(this).parents(".predictive-results").remove();
            (reqTypeaheadBox).focus();

            /* 6523 - pFinder( SWD) with typeahead functionality
             if it is pfinder then navigate to SWD step 2 page
             series = us-en/drivers/selfservice/hp-deskjet-d2600-printer-series/3742933
             model = us-en/drivers/selfservice/hp-deskjet-d2600-printer-series/3742933/model/3742935
                nodeDepth = 4 for SKU
                        = 6 for product
                        = 2 for series
            */
            //https://g9t0144.houston.hp.com/apps/Nav?h_client=s-a-r11839-1&h_product=5436977&h_lang=en&h_cc=us&h_pagetype=s-017
            var searchQuery = $("input[name='searchQuery']");
            if(searchQuery && reqTypeaheadBox.hasClass("pfinder-search") && comingFromPFinder ) {
                var prodIdSelectedTypeahead = $(this).data("productid");
                var separator = "/";
                var url = document.location.origin + separator;
                var cCode = getCCLC("cc") ;
                var lCode = getCCLC("lc");
                //Checking for special cc lc conditions
                /*if(cCode == "gb" && lCode == "en"){
                    cCode = "uk" ;
                }
                else{
                    lCode = localeConversion(cCode,lCode);
                } */
                url += cCode + "-";
                url += lCode + separator;

                var pageIdentifier = $('#pageIdentifier').val().toLowerCase();
                var urlIdentifier = document.location.href;

                //adding url creation code for contact-hp
                /*if(pageIdentifier == "contact hp - anonymous" || urlIdentifier.indexOf("contact-hp") != -1){
                    url += "contact-hp/product" + separator;
                }*/

                if(pageIdentifier == "swdselfservice" || urlIdentifier.indexOf("drivers") != -1){
                    url += "drivers/selfservice" + separator; // has to come from SSC - TBD
                }

                /*else if(pageIdentifier == "identifyproduct" || urlIdentifier.indexOf("products") != -1 ){
                    url += "product" + separator;
                }*/

                var productIDContact;
                var seriesIDContact;
                var skuIDContact;

                console.log(urlCreationFilteredData);
                if(urlCreationFilteredData) {
                    var title;
                    if(urlCreationFilteredData.length >= 1) {
                        $.each(urlCreationFilteredData, function(index, obj) {
                        var data = urlCreationFilteredData[index];
                        if(data.id == prodIdSelectedTypeahead) {
                            // looping each prod id from response json to match with prod id of clicked typeahead selection
                            // url for series
                            /*6594 - url creation using seofriendlyname*/
                            if(data.seoFriendlyName!=undefined) {
                                title = data.seoFriendlyName;
                            } else {
                                title = data.seriesName;
                                title = title.replace(/ /g,"-");
                            }

                            url += title + separator;
                            url += data.seriesId + separator;
                            seriesIDContact = data.seriesId;

                            if(data.classType == 3 || data.classType == 4) {
                                url += "model" + separator;
                                url += data.productId;
                                productIDContact = data.productId;
                            }
                            if(data.classType == 4) {
                                url += "?sku=";
                                url += data.skuId;
                                skuIDContact = data.skuId;
                            }
                            return false;
                        }
                        });
                    } else {
                        /*6594 - url creation using seofriendlyname*/
                        if(urlCreationFilteredData.seoFriendlyName!=undefined) {
                            title = urlCreationFilteredData.seoFriendlyName;
                        } else {
                            title = urlCreationFilteredData.seriesName;
                            title = title.replace(/ /g,"-");
                        }

                        url += title + separator;
                        url += urlCreationFilteredData.seriesId + separator;
                        seriesIDContact = urlCreationFilteredData.seriesId;

                        if(urlCreationFilteredData.classType == 3 || urlCreationFilteredData.classType == 4) {
                            url += "model" + separator;
                            url += urlCreationFilteredData.productId;
                            productIDContact = urlCreationFilteredData.productId;
                        }
                        if(urlCreationFilteredData.classType == 4) {
                            url += "&sku=";
                            url += urlCreationFilteredData.skuId;
                            skuIDContact = urlCreationFilteredData.skuId;
                        }
                    }
                    //adding url creation code for contact-hp
                        //var pageIdentifier = $('#pageIdentifier').val().toLowerCase();
                        //var redirectHubUrl = '<hp:configuration name="HUB_NAV_URL" typeEnum="${'PROPERTY'}" />';
                        //var redirectHubUrl = "http://g9t0144.houston.hp.com/apps/Nav?h_client=s-a-r11839-1" ;
                        var redirectHubUrl =  hubNavigationBaseUrl ;
                        if(productIDContact != undefined){ //no product oid is returned by Idol
                                redirectHubUrl +=  "&h_product=" + productIDContact;
                        }
                        else{
                                redirectHubUrl +=  "&h_product=" + seriesIDContact;
                        }
                        //Checking for special cc lc conditions
                        if(cCode == "gb" && lCode == "en"){
                            cCode = "uk" ;
                        }
                        else{
                            lCode = localeConversion(cCode,lCode);
                        }
                        redirectHubUrl += "&h_lang=" + lCode +"&h_cc=" + cCode ;


                        if(pageIdentifier == "contact hp - anonymous" || urlIdentifier.indexOf("contact-hp")!= -1){
                           redirectHubUrl += "&h_pagetype=s-017";
                           if (skuIDContact!= undefined){
                            redirectHubUrl += "&sku=" + skuIDContact;
                           }
                           console.log(redirectHubUrl);
                           window.location.href = redirectHubUrl;
                        }else if(pageIdentifier == "identifyproduct" 
                        	// It's not SWD landing but the Products landing
                        	|| (urlIdentifier.indexOf("products") != -1 && urlIdentifier.indexOf("/drivers/products") == -1) ){
                           redirectHubUrl += "&h_pagetype=s-001";
                           if (skuIDContact!= undefined){
                            redirectHubUrl += "&sku=" + skuIDContact;
                           }
                           console.log(redirectHubUrl);
                           window.location.href = redirectHubUrl;
                        }else{
                           // if url contains '/' at end, remove it
                            var urlLastIndex = url.length - 1;
                            if(url.charAt(urlLastIndex) == separator) {
                                url = url.substr(0,urlLastIndex);
                            }
                            console.log(url);
                            window.location.href = url;
                        }
                }
            }
            else {
                (reqTypeaheadBox).parents("form").submit();
            }

        });
// keyboard events on the predictive results
    $(document).on("keydown","." + typeAheadObjClass + " li a",function(event) {
                        event.stopPropagation();
                        event.preventDefault();

                        if ((event.which == KEY.DOWN)) {

                            if (!($(document.activeElement).parents("li")
                                    .is(':last-child'))) {
                                /*3244 start: stop all handlers from being executed in DOM tree*/
                                event.stopImmediatePropagation();
                                /*3244 end*/
                                $(document.activeElement).parents("li").find("a").removeClass("hover");
                                $(document.activeElement).parents("li").next().children("a").addClass("hover");
                                $(document.activeElement).parents("li").next().children("a").focus();

                                /*For d-3589 */
                                $(document.activeElement).closest(".hasTypeahead").find("input.oneboxtextsearch").val($(document.activeElement).text());
                                // $(".typeAheadBox").val($(document.activeElement).text());
                                //(reqTypeaheadBox).val($(document.activeElement).text());
                            } else {
                                $("." + typeAheadObjClass + " li a").removeClass("hover");
                                (reqTypeaheadBox).focus();
                                (reqTypeaheadBox).val(currentValue);
                                // autocomplete(reqTypeaheadBox,
                                // typeAheadObjClass);

                            }
                        }
                        else if(event.which == KEY.TAB){
                            var clearIcon = (reqTypeaheadBox).parents(".search-bg").find(".clear-search");
                            if($(clearIcon).length > 0 ){
                                $(clearIcon).focus();
                                }
                            $("." + typeAheadObjClass).remove();


                        }
                        else if ((event.which == KEY.UP)) {
                            if (!($(document.activeElement).parents("li")
                                    .is(':first-child'))) {
                                /*3244 start: stop all handlers from being executed in DOM tree*/
                                event.stopImmediatePropagation();
                                /*3244 end*/
                                $(document.activeElement).parents("li").find("a").removeClass("hover");
                                $(document.activeElement).parents("li").prev().children("a").addClass("hover");
                                $(document.activeElement).parents("li").prev().children("a").focus();

                                /*For d-3589 */
                                $(document.activeElement).closest(".hasTypeahead").find("input.oneboxtextsearch").val($(document.activeElement).text());
                                // $(".typeAheadBox").val($(document.activeElement).text());
                                //(reqTypeaheadBox).val($(document.activeElement).text());
                            } else {
                                $("." + typeAheadObjClass + " li a").removeClass("hover");
                                (reqTypeaheadBox).focus();
                                (reqTypeaheadBox).val(currentValue);
                                // autocomplete(reqTypeaheadBox,
                                // typeAheadObjClass);

                            }
                        } else if (event.which == 13) {
                            $(document.activeElement).trigger("click");
                        }
                    });
}


// This function makes the ajax call for typeahead
function autocomplete(currentInput, typeAheadObjClass) {
    $("." + typeAheadObjClass + "").remove();
     // encoding the value for typeAhead
    currentValue =encodeURIComponent($.trim((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 requestJson = JSON.stringify(ajaxParam.paramData);


    var successHandlerParams = {
            'currentValue':currentValue,  //changed the currentValue as modifiedCurrentValue is not required now.
            'currentInput':currentInput,
            'typeAheadObjClass':typeAheadObjClass
           };

    abortAjaxUtil(); // abort called to abort any previous typeahead ajax call
    //base URL from portal
	var typeaheadAccessToken = $("#accessTokenId").val();
    var url1 = ajaxParam.url1;          //commenting for now since url is hardcoded for US 88656 KAAS API integration
   // var url1 = "https://ppssupport-qaauth.houston.hpicorp.net/typeahead?q=<text>&resultLimit=10&store=tmsstore&language=en&printFields=tmspmnamevalue,title,body,childnodes,class,productid,seofriendlyname,shortestnavigationpath";   //hardcoding new TA url for testing purpose for US 88656
    ajaxParam.url = url1;
    ajaxParam.url = ajaxParam.url.replace("<text>",currentValue);   //Change as part of US 88656 KAAS API integration
    //ajaxParam.url = ajaxParam.url.replace("<accessToken>",typeaheadAccessToken);

	// if the user is on us-en/drivers/printer /laptop etc. for US 97381 find my product - include filters for TA
        var filterId = getFilterIdForDriversPage();
        //Appending the filterId for US 97381 find my product - include filters for TA
        var filterString = '';
    	if (filterId !== null && filterId !== ' ' && filterId !== "") {
    		filterString = "navigationpath:(" + filterId + ") AND ";
    	}
    	var indexOfFilter = ajaxParam.url.indexOf("&filters=");
    	var filterTxt = "&filters=";
    	var filterLength = indexOfFilter + filterTxt.length;
    	var url1 = ajaxParam.url.slice(0, filterLength);
    	var url2 = ajaxParam.url.slice(filterLength, ajaxParam.url.length);
    	if (filterString !== '') {
    		ajaxParam.url = url1 + filterString + url2;
    	} else {
    		ajaxParam.url = url1 + url2;
    	}
              
    // Make the call here
    callAjaxUtil('typeahead',ajaxParam.url,'GET',recallSearch,'JSON',null,successHandlerParams,ajaxFailureHandler); //Adding GET as part of US 88656 KAAS API integration
    $(currentInput).parent(".hasTypeahead").find(".searching").show();
}

var getFilterIdForDriversPage = function(){			//moved this function outside for US 97381: fnd my product - include TA filters.
	
	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;		
	}
	if(url.indexOf('contact/printers') > 0){
		
		id = printerId;	
	}else if(url.indexOf('contact/laptops') > 0){
		
		id = laptopId;	
	}else if(url.indexOf('contact/desktops') > 0){
		
		id = desktopId;		
	}
	
	return id;
}
/*This function takes the IDOL JSON response and makes sense out of it.*/
var RELEVANT_DIFF;  // stores the relevance diff from jsp  as part of US 88656 Kaas API integration
var TYPEAHEAD_MAX_LIMIT = 6; //to be externalized.changed the limit to 6. changes in response rendering as part of US 88656 Kaas API integration

/**
 *  This method is used when hp-core-service is utilized
 *  for type ahead in search.
 *  This method populates type ahead.
 *
 *  @since R3.0
 *  @author arka.sinha@hp.com
 */
var nonIdolTypeAhead = function(data,successHandlerParams){

    var extractedData = [];
    for (var i=0; i<data.length; i++){

            extractedData.push(data[i].matchResut);


    }
    if(extractedData.length > 0){
        createList(extractedData, extractedData.length, successHandlerParams.currentInput, successHandlerParams.currentValue, successHandlerParams.typeAheadObjClass);
    }
}

var recallSearch = function(data,successHandlerParams){
    var totalResults;


     var responseDataJSON = data.matches;   // changes in response rendering as part of US 88656 Kaas API integration

    /*if(typeof(responseDataJSON)=='object'){                    // changes in response rendering as part of US 88656 Kaas API integration
            responseDataJSON = responseDataJSON.join();
    }

    responseDataJSON = $.parseJSON(responseDataJSON);*/

    /* responseDataJSON = data; */
    if(!(responseDataJSON == undefined)){ // // changes in response rendering as part of US 88656 Kaas API integration
    totalResults = responseDataJSON.length;
    }
    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

            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,'JSON',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.matches;   // changes in response rendering as part of US 88656 Kaas API integration

    /*       responseDataJSON = responseDataJSON.join();
    }

    responseDataJSON = $.parseJSON(responseDataJSON);*/
    /* responseDataJSON = rawData; */
    if(!(responseDataJSON == undefined)){ // changes in response rendering as part of US 88656 Kaas API integration
    totalResults = responseDataJSON.length;
    }
    else{
        totalResults = 0;
    }

    var lowestNodeDepth = 0;
    var lowestNodeDepthCount = 0;
    var maxWeightage = 0.0;
    var typeaheadResultCounter = 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 != undefined) ? true : false;                     // changes in response rendering as part of US 88656 Kaas API integration
            if (isMultipleResult) { 
                $.each(rawData, function(index, obj) {
                    var tempData = {};
                    var tempDataforURL = {};

                    var elemNavPathValue = ((this.shortestNavigationPath).split('|').length) - 2; //having a -2 as an empty string is created after the last '|'
                    var elemClazzType = this.pmClass;
                    var shortestNavPathLength = calcNodeDepth(elemClazzType, elemNavPathValue);


                    var weightage = this.matchScore;						// changes in response rendering as part of US 88656 Kaas API integration
                    var nodeDepth = shortestNavPathLength;


                    tempData["title"] = this.name;
                    tempData["nodeDepth"] = nodeDepth;
                    tempData["weightage"] = weightage;
                    tempData["product"] = (checkValidity(this.productId)) ?  this.productId : "";
                    if (maxWeightage == 0.0) {
                        maxWeightage = weightage;
                        if(relevanceDifference == null || relevanceDifference == ""){
                        	relevanceDifference = 10;
                        }
                        RELEVANT_DIFF = relevanceDifference;  //capturing the relevance diff from jsp
                        RELEVANT_DIFF = (RELEVANT_DIFF * maxWeightage)/100;
                        relevantDataIntrim.push(tempData);
                        lowestNodeDepth = nodeDepth;

                        if(this.childnodes)
                        {														
                          var childArray=this.childnodes.split('|');
                          childNodeParentArray.push(childArray);
                        }

                    } else if ((maxWeightage - weightage) < RELEVANT_DIFF) {



                    	if (nodeDepth <= lowestNodeDepth) {
                            relevantDataIntrim.push(tempData);
                            lowestNodeDepth = nodeDepth;
                        }
                        else if (nodeDepth - lowestNodeDepth == 1) {
                            relevantDataIntrim.push(tempData);
                        }

                    	 if(this.childnodes)
                       {
                            var childArray=this.childnodes.split('|');
                            childNodeParentArray.push(childArray);
                        }

                    }

                     /*6523 - in case of pfinder, storing results for forming URL of drivers page (on click
                    of typeahead results)*/
                    tempDataforURL["seriesName"] = tempData["title"];
                    tempDataforURL["classType"] = shortestNavPathLength;
                    var seriesId;

                    /*6594 - url creation using seofriendlyname */
                    if(this.seoFriendlyName == undefined){
                        tempDataforURL["seoFriendlyName"] = "null"; //If no seoFriendlyName is found, use null
                    }
                    else{
                        tempDataforURL["seoFriendlyName"] = this.seoFriendlyName;
                    }

                    if(shortestNavPathLength == 2) {
                        tempDataforURL["seriesId"] = tempData["product"];
                        tempDataforURL["id"] = tempData["product"];
                    } else if(shortestNavPathLength == 3 || shortestNavPathLength == 4) {		//code optimization for US 88656
                        tempDataforURL["productId"] = tempData["product"];
                        tempDataforURL["id"] = tempDataforURL["productId"];
                        seriesId = this.shortestNavigationPath;
                        seriesId = (checkValidity(seriesId)) ? seriesId.split("|") : "";
                    }
                    if(shortestNavPathLength == 3) {
                        
                        seriesId == "" ? "" : (seriesId = seriesId[seriesId.length-3]);
                        tempDataforURL["seriesId"] = seriesId;
                    }
                    
                    if(shortestNavPathLength == 4) {
                        tempDataforURL["skuId"] = tempData["title"];
                        seriesId == "" ? "" : (seriesId = seriesId[seriesId.length-4]);
                        tempDataforURL["seriesId"] = seriesId;
                        var productId = this.shortestNavigationPath;
                        productId = (checkValidity(seriesId)) ? productId.split("|") : "";
                        productId == "" ? "" : (productId = productId[productId.length-3]);
                        tempDataforURL["productId"] = productId;
                    }
                    urlCreationTempData.push(tempDataforURL);
                     /* 6523 - in case of pfinder, storing results for forming URL of drivers page (on click
                    of typeahead results - End */

                });



            } else {
                var tempData = {};
                var tempDataforURL = {};				// changes in response rendering as part of US 88656 Kaas API integration

                var elemNavPathValue = ((rawData.shortestNavigationPath).split('|').length) - 2; //having a -2 as an empty string is created after the last '|'
                var elemClazzType = rawData.pmClass;
                var shortestNavPathLength = calcNodeDepth(elemClazzType, elemNavPathValue)



                var weightage = rawData.matchScore;
                tempData["title"] = rawData.name;
                tempData["nodeDepth"] = shortestNavPathLength;
                tempData["weightage"] = weightage;
                tempData["product"]= (checkValidity(rawData.productId)) ? rawData.productId : "" ;
                lowestNodeDepth = shortestNavPathLength;
                relevantDataIntrim.push(tempData);

                tempDataforURL["seriesName"] = tempData["title"];
                tempDataforURL["classType"] = shortestNavPathLength;

                /*6594 - url creation using seofriendlyname*/
                tempDataforURL["seoFriendlyName"] = rawData.seoFriendlyName;

                if(shortestNavPathLength == 2) {
                    tempDataforURL["seriesId"] = tempData["product"];
                } else if(shortestNavPathLength == 3) {
                    tempDataforURL["productId"] = tempData["product"];
                    var seriesId = rawData.shortestNavigationPath;
                    seriesId = (checkValidity(seriesId)) ? seriesId.split("|") : "";
                    seriesId == "" ? "" : (seriesId = seriesId[seriesId.length-3]);
                    tempDataforURL["seriesId"] = seriesId;
                    tempDataforURL["id"] = tempDataforURL["productId"];
                }
                else if(shortestNavPathLength == 4) {
                        tempDataforURL["skuId"] = tempData["title"];
                        tempDataforURL["productId"] = tempData["product"];
                        tempDataforURL["id"] = tempDataforURL["productId"];

                        var seriesId = rawData.shortestNavigationPath;
                        seriesId = (checkValidity(seriesId)) ? seriesId.split("|") : "";
                        seriesId == "" ? "" : (seriesId = seriesId[seriesId.length-4]);
                        tempDataforURL["seriesId"] = seriesId;
                        var productId = rawData.shortestNavigationPath;
                        productId = (checkValidity(seriesId)) ? productId.split("|") : "";
                        productId == "" ? "" : (productId = productId[productId.length-3]);
                        tempDataforURL["productId"] = productId;
                }
                urlCreationTempData.push(tempDataforURL);
            }
            urlCreationFilteredData = urlCreationTempData;



            $.each(relevantDataIntrim, function(index, obj) {

                                //filter relevantDataIntrim object user story 6523
                var isChildItem = false;
                this["product"] = this["product"].toString();			//converting the productId to string for comparison for US 88656
                // check whether the product is child item  from childnode array
                for(var i=0;i < childNodeParentArray.length;i++)
                {
                   if(childNodeParentArray[i].indexOf(this["product"]) > -1)
                   {
                        isChildItem = true;
                         break;
                   }
                }
                ///if this item is a child item den discard
                if(isChildItem)
                {
                    return true;
                }
                ////// end 6523



                if (typeaheadResultCounter < TYPEAHEAD_MAX_LIMIT) {
                	
                //FIX for ALM 2567- removing the node depth condition
                    
                    	typeaheadResultCounter++;
                        var tempData = {};
                        tempData["label"] = this["title"];
                        tempData["productId"] = this["product"];
                        relevantData.product.suggestions.push(tempData);	
                    }
                
                    else {
                    return false;
                }
            });
            getMatch(relevantData,successHandlerParams);
        }
    }


}
/*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 = "<ul class=\"predictive-results " + typeAheadObjClass
            + " \" style=\"left:"+typeaheadLeftHook+"\">";
    }
    else{
        var stringList = "<ul class=\"predictive-results " + typeAheadObjClass
        + " \" style=\"right:"+typeaheadLeftHook+"\">";
    }
    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 += " <li><a href=\"javascript:void(0);\" class=\"firstTopic\" \">"
                    + jsonObj[i] + "</a></li> ";
        } else {
            stringList += " <li><a href=\"javascript:void(0);\" data-productid=\""+jsonObj[i].productId+"\" >" + jsonObj[i].label
                    + "</a></li> ";
        }
    }
    stringList += "</ul>"
    if ((currentValue != "") && (jsonLen != 0)) {
        if ((currentValue.toLowerCase() != jsonObj[0].label.toLowerCase())) {
            (currentInput).parents(".hasTypeahead").append(stringList);
            if( (currentInput).hasClass("pfinder-search") ){
                comingFromPFinder=true;
            }
            else{
                comingFromPFinder=false;
            }
        }
    }
    // $(".autoCompleteList").css("top", (currentInput).css("height"));
    // $(".typeAheadBox").val(jsonObj[0]);

}

//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</strong> from
    the suggestedStr
 */
function createSuggestedArr(suggestedStr) {
    var startTag = "<strong>";
    var lastTag = "</strong>";
    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></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></strong> to the keyword
             * based on its "keyword+</strong>" occurrence
             */
            else {
                var index = suggestedStr.lastIndexOf(toBeHighlighted+'</strong>');
                if (index != -1) {
                    firstPartStr = suggestedStr.substring(0, index);
                        lastPartStr = suggestedStr.substring(index);
                        suggestedStr = firstPartStr
                            + createHiglightedStr(lastPartStr, toBeHighlighted);
                }
            }
        }

        finalSuggestedStr = finalSuggestedStr + suggestedStr;
    }

    return finalSuggestedStr;
}

/*created for typeahead keyword highlighting - Richa
 * this function adds strong tag around matching text
 * */
function createHiglightedStr(strValue, toBeHighlighted) {
    var startTag = "<strong>";
    var lastTag = "</strong>";
    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 fieldTextParamString = '+AND+STRING{';			
			var i = url.indexOf(fieldTextParamString);
			i = i + fieldTextParamString.length;
			var j = url.indexOf('}:NAVIGATIONPATH');
			
			finalUrl = url.slice(0, i) + filterId + url.slice(j, url.length);			
		}
	}
	
	return finalUrl;
}

/**
 * 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);
}
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{/* 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 arka.sinha@hp.com
 *
 */
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;
	    	}
	    	console.log(responseData);
	    	populateSSID();
	    	callback(productNumberRequest,responseData);
	    },
	    error : function(e) {

	    	responseData.error = 'service error';
	        console.log('ERROR: ', e);
	        console.log(xhr.status);
	        populateSSID();
	        var errorData = {		//creating the json object and appending source for  ALM 2866 500 error analysis
	        		"requestUrl" : url,
	        		"data": JSON.stringify(requestJSON),
	        		"errorReason":e.responseText
	        };
	        localStorage.productNumberConversionServiceError = JSON.stringify(errorData);
	        
	        callback(productNumberRequest,responseData);
	    },
	    complete : function(e) {
	    	$("#conversionGifSpinner").modal("hide");
	    }
    });
}

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 badal.sharma@hp.com
 *
 */
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;
	    	}
	    	console.log(responseData);
	    	populateSSID();
	    	callback(serialNumberRequest,responseData);
	    },
	    error : function(e) {

	    	responseData.error = 'service error';
	        console.log('ERROR: ', e);
	        console.log(xhr.status);
	        populateSSID();
	        var errorData = {		//creating the json object and appending source for  ALM 2866 500 error analysis
	        		"requestUrl" : url,
	        		"data": JSON.stringify(requestJSON),
	        		"errorReason":e.responseText
	        };
	        localStorage.serialNumberConversionServiceError = JSON.stringify(errorData);
	        
	        callback(serialNumberRequest,responseData);
	    },
	    complete : function(e) {
	    	$("#conversionGifSpinner").modal("hide");
	    }
    });
}

}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{
/*----------------------- SMO with split hpi and hpe --------------------------*/

 paintPFinderResultsWithSplit = function (jsonData,categorylistheading) {
	    var totalResCount = 0;
	    var globalLength=0;
	    var localLength=0;
	    var categoriesLength = 0;
	    if (!(jsonData.pfinder.local.categories[0] == undefined)) {
	
	        var localCategories = jsonData.pfinder.local.categories;
	        var categoryString = "";
	                
	        $.each(localCategories, function(index, obj) {
	            if(isSWDPage()){
	                 categoryString = categoryString + createSWDCategoryListWithSplit(index, obj,categorylistheading);
	            }
	            else{
	                 categoryString = categoryString + createCategoryListWithSplit(obj,categorylistheading);
	            }
	           
	            localLength = localLength + getResultCountWithSplit(obj);
	        });
	        
	        $(".localResults").append(categoryString);
	        $(".localResultsHolder").text("("+localLength+")");
	        $(".localResults").css("display","block");       
	
	        if(isSWDPage()){
	            //open the first dropdown if length = 1
	            if(localCategories.length==1){
	                var panelAnchor = $('.pFinderResults .hp-section-md .panel-title a')[0];
	                var panelTitle = $('.pFinderResults .hp-section-md .panel-title')[0];
	                var panelCollapse = $('.pFinderResults .hp-section-md .panel-collapse')[0];
	
	
	                $(panelAnchor).addClass('toggled');
	                $(panelAnchor).attr("aria-expanded","true");
	                $(panelTitle).addClass('open');
	                $(panelCollapse).addClass('in').removeAttr('style');
	
	            }    
	        }
	        
	        
	
	    }
	
	    if (!(jsonData.pfinder.worldwide.categories[0] == undefined)) {     
	        var globalCategories = jsonData.pfinder.worldwide.categories;
	        var categoryString = "";
	
	        $.each(globalCategories, function(index, obj) {
	            categoryString = categoryString + createCategoryList(obj);
	            globalLength = globalLength + getResultCount(obj);
	        });
	        $(".globalResults").append(categoryString);
	        $(".globalResultsHolder").text("("+globalLength+")");
	        $(".globalResults").css("display","block");     
	    }
	    
	    categoriesLength = jsonData.pfinder.worldwide.categories.length + jsonData.pfinder.local.categories.length ;
	    
	    if(categoriesLength == 1){
	        setTimeout(function() {
	        $(".hp-expand-colapse").trigger("click");
	        },100);
	    }
	    
	    totalResCount = globalLength + localLength;
	    $(".totalResCountHolder").text("("+totalResCount+")");
	};

 
 createCategoryListWithSplit = function(categories,categorylistheading) {
    var builtString;
    var productsLength = getResultCountWithSplit(categories);
    builtString = "<div class=\"pFinderCategory\"><div class=\"hp-expandable-wrapper\">\
    <a class=\"hp-expand-colapse rtlTextWrapper\"><span class=\"linkText \"><span class=\" rtlAlignText \">"
        + categories.category.name + "</span><span class=\"rtlAlignText\"> ("+ productsLength +")\
    </span></span><span class=\"expandIcon\"></span></a>\
    <div class=\"hp-expandable-section\"><ul class=\" list-wrapper\">";
    
    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 + '            </ul>'+
                                '</div>'+
                              '</div>'+
                        '</div>';
        return builtString;
    
    }

 };

 createSWDCategoryListWithSplit = function(index, categories,categorylistheading){

    var builtString;
    var productsLength = getResultCountWithSplit(categories);

    builtString = '<div class="panel">'+
                      '<div class="panel-heading">'+
                        '<h4 class="panel-title">'+
                          '<a aria-expanded="false" data-toggle="collapse" href="#pfinderAccordian'+index+'" class="">' + categories.category.name  +' <span class="count">('+productsLength+')</span></a>'+
                        '</h4>'+
                      '</div>'+

                      '<div id="pfinderAccordian'+index+'" class="panel-collapse collapse" style="display: none;">'+
                        '<div class="panel-body">'+
                          '<ul>';

    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);
            }
             else if(key=="hpeProducts"&& val.length>0){
            	 hpeString +=  otherProducts("",val,key,categorylistheading); 
               }    
        }

        builtString += hpiString+hpeString + '            </ul>'+
                                '</div>'+
                              '</div>'+
                        '</div>';
        return builtString;
    
    }

};

 getResultCountWithSplit = function(categories){
    var len= categories.category.hpiProducts.length + categories.category.hpeProducts.length;
    return len;
 };

 otherProducts = function(accrodianstring,val,productType,categorylistheading){
    if(productType=="hpiProducts")
    {
        accrodianstring += "<li><h4 class='h4font'>"+categorylistheading.hpiProducts+"</h4></li>";
    }
    else if(productType=="hpeProducts") {
        accrodianstring += "<li><h4 class='h4font'>"+categorylistheading.hpeProducts+"</h4></li>";
    }

     $.each(val, function(index, obj) {
      accrodianstring += "<li><a href='" + obj.product.url + "'>" + obj.product.productName + "</a></li>"
    });

    return accrodianstring; 
 };


/*----------------------- end SMO with split hpi and hpe --------------------------*/


/*----------------------- old structure --------------------------*/

 paintPFinderResults = function(jsonData) {
	var totalResCount = 0;
	var globalLength=0;
	var localLength=0;
	var categoriesLength = 0;
    if (!(jsonData.pfinder.local.categories[0] == undefined)) {

        var localCategories = jsonData.pfinder.local.categories;
        var categoryString = "";
                
        $.each(localCategories, function(index, obj) {
            
            //US 5247: always create the SWD experience - HH
            categoryString = categoryString + createSWDCategoryList(index, obj);
           
            localLength = localLength + getResultCount(obj);
        });
        
        $(".localResults").append(categoryString);
        $(".localResultsHolder").text("("+localLength+")");
        $(".localResults").css("display","block");       

        //US 5247: always create the SWD experience - HH
        //removed the if(SWDPage) condition
            //open the first dropdown if length = 1
            if(localCategories.length==1){
                var panelAnchor = $('.pFinderResults .hp-section .panel-title a')[0];
                var panelTitle = $('.pFinderResults .hp-section .panel-title')[0];
                var panelCollapse = $('.pFinderResults .hp-section .panel-collapse')[0];


                $(panelAnchor).addClass('toggled');
                $(panelAnchor).attr('aria-expanded',"true");
                $(panelTitle).addClass('open');
                $(panelCollapse).addClass('in').removeAttr('style');

            }    
        
        
        

    }

    if (!(jsonData.pfinder.worldwide.categories[0] == undefined)) {  	
        var globalCategories = jsonData.pfinder.worldwide.categories;
        var categoryString = "";

        $.each(globalCategories, function(index, obj) {
            categoryString = categoryString + createCategoryList(obj);
            globalLength = globalLength + getResultCount(obj);
        });
        $(".globalResults").append(categoryString);
        $(".globalResultsHolder").text("("+globalLength+")");
        $(".globalResults").css("display","block");     
    }
    
    categoriesLength = jsonData.pfinder.worldwide.categories.length + jsonData.pfinder.local.categories.length ;
    
    if(categoriesLength == 1){
    	setTimeout(function() {
    	$(".hp-expand-colapse").trigger("click");
    	},100);
    }
    
    totalResCount = globalLength + localLength;
    $(".totalResCountHolder").text("("+totalResCount+")");
}

function createCategoryList(categories) {
    var builtString;
    var productsLength = getResultCount(categories);
    builtString = "<div class=\"pFinderCategory\"><div class=\"hp-expandable-wrapper\">\
    <a class=\"hp-expand-colapse rtlTextWrapper\"><span class=\"linkText \"><span class=\" rtlAlignText \">"
        + categories.category.name + "</span><span class=\"rtlAlignText\"> ("+ productsLength +")\
    </span></span><span class=\"expandIcon\"></span></a>\
    <div class=\"hp-expandable-section\"><ul class=\" list-wrapper\">";
    var productsInCategory = categories.category.products;
    $.each(productsInCategory, function(index, obj) {
        builtString += "<li><a href='" + obj.product.url + "'>" + obj.product.productName + "</a></li>"
    });

    builtString += "</ul></div></div></div>"
    return builtString;
}


function createSWDCategoryList(index, categories){

    var builtString;
    var productsLength = getResultCount(categories);

    builtString = '<div class="panel">'+
                      '<div class="panel-heading">'+
                        '<h4 class="panel-title">'+
                          '<a data-toggle="collapse" href="#pfinderAccordian'+index+'" class="">' + categories.category.name  +' <span class="count">('+productsLength+')</span></a>'+
                        '</h4>'+
                      '</div>'+

                      '<div id="pfinderAccordian'+index+'" class="panel-collapse collapse" style="display: none;">'+
                        '<div class="panel-body">'+
                          '<ul>';
                                
    var productsInCategory = categories.category.products;
    $.each(productsInCategory, function(index, obj) {
        builtString += "<li><a href='" + obj.product.url + "'>" + obj.product.productName + "</a></li>"
    });

    builtString += '            </ul>'+
                            '</div>'+
                          '</div>'+
                    '</div>';
    return builtString;



}

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(){

    return true;
/*    var pageName = $('#pageIdentifier').val()

    if(pageName.indexOf('SWD')==0){
        return true;
    }
    else{
        return false;
    }*/


}
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{/*
$(document).ready(function() {
    autocompleteSR();

});

function autocompleteSR() {

    $.ajax({
        type: 'POST',
        url: "js/searchResult.json",
        dataType: 'JSON',
        success: function(results) {
            paintSearchResults(results);
        },
        error: function(xml, status, error) {
            //$(".hasTypeahead .searching").hide();
        }
    });

   
}*/

function paintSearchResults(jsonData) {
    JsonData2 = jsonData;
    
    if (!(jsonData.searchResultObjArr == undefined)) {

        var searchResults = jsonData.searchResultObjArr;
        var searchResultMarkupString = "";
        var searchResultsPromotion = "";
        var searchResultsOrganic = "";


        $.each(searchResults, function(index, obj) {
        	var resultObj = obj.searchResult;
    		if((typeof(resultObj.searchId) == "undefined") && (typeof(resultObj.searchType) == "undefined")){
    			searchResultsOrganic = searchResultsOrganic + createSearchResultMarkup(obj);
    		}
    		else if((typeof(resultObj.searchId) == "undefined") && (typeof(resultObj.searchType) != "undefined")
    		&& (resultObj.searchType=="promotion")){
    			searchResultsPromotion = searchResultsPromotion + createSearchResultMarkup(obj);
    		}
    		else{
    			searchResultsPromotion = searchResultsPromotion + createSearchResultMarkup(obj);
    		}

            // searchResultMarkupString = searchResultMarkupString + createSearchResultMarkup(obj);
        });
        if(promoIdsArr.length != 0){
        	globalDataLayer.Search.PromotionIds = promoIdsArr;
        }
        searchResultMarkupString = "<div class='promotionResultsContainer'>"+searchResultsPromotion+"</div><div class='organicResultsContainer'>"+searchResultsOrganic+"</div>";
        //console.log("search String: "+searchResultMarkupString);
        $("#searchResultsWrapper").append(searchResultMarkupString);
        $(".search-result:not(:last)").after("<hr class=\"results-hr\" />");
        
    }
    
    // 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
		if(link.indexOf("hpicorp.net")> -1){							// fix for bug 98597
		    var regex = new RegExp("([\w0-9._:/-]+hpicorp.net(.*))");		//regex for lower environments
		}else if(link.indexOf("amazonaws.com")> -1)
		{
		    var regex = new RegExp("([\w0-9._:/-]+amazonaws.com(.*))");
		}else if(link.indexOf("cloudfront.net")> -1)
		{
			//Added condition for groomed sdl pdf url
		    var regex = new RegExp("([\w0-9._:/-]+cloudfront.net(.*))");
		}else{
			var regex = new RegExp("([\w0-9._:/-]+hp.com(.*))");
		}

		if(link.indexOf('http') > -1 && !regex.test(link)){
			$(this).append(' <i class="icon-external-link"></i>');
		}
	});

}

var promoIdsArr = [];
function createSearchResultMarkup(searchResultsObj) {
    var builtString;
    var resultObj = searchResultsObj.searchResult;
    console.log(resultObj);
    if((typeof(resultObj.searchId) == "undefined") && (typeof(resultObj.searchType) == "undefined")){
    	var Url= resultObj.searchURL;
    	var splitUrl = Url.split("/");
    	var docID = splitUrl[splitUrl.length - 1];
    	console.log(docID);
    	var splitPdf=docID.split(".");
    	if(splitPdf[splitPdf.length -1]=="pdf")
    		{
    		builtString = "<div organic-search-id="+docID+" class='search-result pagination-item'><a target='_blank' href= "+resultObj.searchURL+">" + resultObj.searchTitle +"</a><p>"+resultObj.searchDesc+"</p></div>";
    		}else{
    	 builtString = "<div organic-search-id="+docID+" class='search-result pagination-item'><a href= "+resultObj.searchURL+">" + resultObj.searchTitle +"</a><p>"+resultObj.searchDesc+"</p></div>";
    		}
    }else if((typeof(resultObj.searchId) == "undefined") && (typeof(resultObj.searchType) != "undefined")
    		&& (resultObj.searchType=="promotion")){
    	 builtString = "<div promotion-id='default-promotion' class='search-result pagination-item'><a href= \""+resultObj.searchURL.replace(/ /g,'%20') +"\">" + resultObj.searchTitle +"</a><p>"+resultObj.searchDesc+"</p></div>";    	  
    	}
    else{
   	 builtString = "<div promotion-id="+resultObj.searchId+" class='search-result pagination-item'><a href= "+resultObj.searchURL.replace(/ /g,'%20')+">" + resultObj.searchTitle +"</a><p>"+resultObj.searchDesc+"</p></div>";    	  
   	 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,searchQuery,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,searchQuery,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);

	/* $('#oneboxtextsearch').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 = $('#oneboxtextsearch').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('<li><a href="javascript:void(0)" class="active"><span style="font-size:0">'+paginationTBK.pages +' </span><span class="pageCount">'+count+'</span><span style="font-size:0px"> ' + paginationTBK.of +  last +'</span></a></li>');
		} else {
			$('.pagination-container ul.pagination-pages').append('<li><a href="javascript:void(0)"><span style="font-size:0">'+paginationTBK.pages +' </span><span class="pageCount">'+count+'</span><span style="font-size:0px"> ' + paginationTBK.of +  last +'</span></a></li>');
		}
	}
 	
	//check for disabling first/last button
	if(current == 1) {
		enableDisablePageButton('disable','less');
	}
	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.pagination-less').attr('disabled','disabled');
			$('.pagination-button.pagination-less').css('background-color','#DDD');
		} else {
			$('.pagination-button.pagination-more').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');

			// enable more
			$('.pagination-button.pagination-more').removeAttr('disabled');
			$('.pagination-button.pagination-more').css('background-color','#FFF');
	}
	
}

/*Pagination - RIcha - end */

function handlePaginationRtl() {
	// RTL for pagination buttons - Richa 
	if($('html').attr('dir') == 'rtl') {
		$('.pagination-button.pagination-less i').removeClass('fa fa-chevron-left').addClass('fa fa-chevron-right');
		$('.pagination-button.pagination-more i').removeClass('fa fa-chevron-right').addClass('fa fa-chevron-left');
	}
	// RTL for pagination buttons - Richa - end
}



}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{$(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();

    });
}

}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{/**
 * 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() {};
    }    
  } 
})();
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{// 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('[data-toggle="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
	};
}());
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{// This has been made obsolete by the addition of iCheck plugin
// Saving code here for backup for now




// Checkboxes = (function(){
// 	var init = function(){
// 		var $inputs = $('input[type="checkbox"]');
// 		if($inputs.length){
// 			$inputs.each(function(){
// 				var $label = $(this).parent('label');
// 				preCheckBox($label);
// 			});
// 			addHandlers();
// 		}
// 	}

// 	var addHandlers = function(){
// 		$('input[type="checkbox"]').parent('label').on('tap click', checkBox);
// 	}
// 	var checkBox = function(e){
// 		e.stopPropagation();
// 		e.preventDefault();
// 		var $label = $(this);
// 		var $input = $label.find('input');
// 		if($input.attr('checked')){
// 			$input.removeAttr('checked').change();
// 			$label.removeClass('selected');
// 		} else {
// 			$input.attr('checked', 'checked').change();
// 			$label.addClass('selected');
// 		}
// 	}
// 	var preCheckBox = function($label){
// 		var $input = $label.find($('input[type="checkbox"]'));
// 		if($input.attr('checked')){
// 			$input.attr('checked', 'checked').change();
// 			$label.addClass('selected');
// 		} else {
// 			$input.removeAttr('checked').change();
// 			$label.removeClass('selected');	
// 		}
// 	}
// 	return {
// 		init: init
// 	}
// }());


  // // ---------------------------------------------- FILTERS-DESKTOP

  // $('.filters-desktop .expandable').on('click touchstart', function(e) {
  //   e.preventDefault();
  //   $(this).toggleClass('open');
  // });

  // $('.filters-desktop .filter-options label').on('click touchstart', function(e) {
  //   e.preventDefault();
  //   $(this).toggleClass('selected');
  // });

  // $('.show-more').on('click touchstart', function(e) {
  //   e.preventDefault();
  //   $(this).closest('.filter-options-nested').find('.more').removeClass('more').addClass('less');
  //   $(this).hide();
  //   $('.show-less').show();
  // });

  // $('.show-less').on('click touchstart', function(e) {
  //   e.preventDefault();
  //   $(this).closest('.filter-options-nested').find('.less').removeClass('less').addClass('more');
  //   $(this).hide();
  //   $('.show-more').show();
  // });

  // $('.show-more-expandables').on('click touchstart', function(e) {
  //   e.preventDefault();
  //   $(this).closest('.filter-level-1').find('.more-category').removeClass('more-category').addClass('less-category');
  //   $(this).hide();
  //   $('.show-less-expandables').show();
  // });

  // $('.show-less-expandables').on('click touchstart', function(e) {
  //   e.preventDefault();
  //   $(this).closest('.filter-level-1').find('.less-category').removeClass('less-category').addClass('more-category');
  //   $(this).hide();
  //   $('.show-more-expandables').show();
  // });

  // // ---------------------------------------------- FILTERS-TRIGGER

  // $('#filter-trigger').on('click touchstart', function(e) {
  //   e.preventDefault();
  //   $('.filters').toggleClass('open');
  // });

  // $('.filters .close').on('click touchstart', function(e) {
  //   e.preventDefault();
  //   $('.filters').removeClass('open');
  // });

  // $('.filters').on('scroll', function(e) {
  //   e.stopPropagation();
  // });

  // // ---------------------------------------------- FILTERS-MOBILE

  // $('#close-tab-content').on('click touchstart', function(e) {
  //   e.preventDefault();
  //   $('.tab-content').removeClass('open');
  // });

  // $('.hp-nav-tabs a').on('click touchstart', function(e) {
  //   e.preventDefault();
  //   $('.tab-content').toggleClass('open');
  // });

  // $('.filter-trigger').on('click touchstart', function(e) {
  //   e.preventDefault();
  //   $('.filters-mobile').toggleClass('open');
  // });

  // $('.filter-title').on('click touchstart', function(e) {
  //   e.preventDefault();
  //   $(this).next('.filter-options').toggleClass('open');
  //   $(this).closest('.filter-category').toggleClass('open');
  // });

  // $('.filter-options label').on('click touchstart', function(e) {
  //   e.preventDefault();
  //   $(this).toggleClass('open');
    
  //   var $filterOption = $(this).find('input[type="checkbox"]');
  //   $filterOption.attr('checked', !$filterOption.is(':checked'));

  //   $(this).next('.filter-options-nested').toggleClass('open');
  // });  

}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{// This component mimics the basic functionality of the bootstrap dropdown component


Dropdown = (function(){
	
	var init = function(){
		if($('[data-toggle="customDropdown"]').length){
			addHandlers();
		}
	};

	var addHandlers = function(){
		$('[data-toggle="customDropdown"]').on('tap click', checkSize);
	
		$('.customDropdown').on('dClose', dClose);
		$('.customDropdown').on('dOpen', dOpen);
		$(document).on('tap click', clearDropdowns);
		$('.customDropdown').on('tap click', function(e){
			e.stopPropagation();

		});
	};

	var checkSize = function(e){
		// if($(window).width() > 767){
			e.preventDefault();
			e.stopPropagation();
			normalDropdown(this);
		// } else {
		// 	mobileDropdown(this);
		// }
	};
	var clearDropdowns = function(e){
		var container = $(".customDropdown");
	    if (!container.is(e.target) // if the target of the click isn't the container...
	        && container.has(e.target).length === 0) // ... nor a descendant of the container
	    {
	        $dropdowns = $('.customDropdown');
			$dropdowns.trigger('dClose');
	    }
	};
	var normalDropdown = function(target){
		$dropdown = $(target).parent();

		$dropdowns = $('.customDropdown');
		if($dropdown.hasClass('open')){
			$dropdown.trigger('dClose');
		} else {
			$dropdowns.not($dropdown).trigger('dClose');
			$dropdown.trigger('dOpen');
		}
	};
	var dClose = function(e){
		e.stopPropagation();
		$this = $(this);
		$this.removeClass('open');
	};

	var dOpen = function(e){
		$this = $(this);
		$this.addClass('open');
	};

	return {
		init: init
	};
}());
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{// 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){
            $('body').removeClass('hp-filter-open');
        }
        else {
          if ($('.filters.open').length) {
            $('body').addClass('hp-filter-open');
          }
        }
      });
    }
  };

  var applyFilter = function(e){
    // make ajax call
    var $input = $(this);
    if($input.is('[data-filter="all"]')){
      $('#filter-form').submit();
    } else {
      $input.parents('.filter-category').find('[data-filter="all"]').icheck('unchecked');
      $('#filter-form').submit();
    }
  };

  var expand = function(e){
    var $expander = $(this);
    if($expander.hasClass('selected')){
      $expander.removeClass('selected');
      $expander.find("a[data-expandable]").attr("aria-expanded","false");
      $expander.siblings('.filter-options-nested').hide();
    } else {
      $expander.addClass('selected');
      $expander.siblings('.filter-options-nested').show();
      $expander.find("a[data-expandable]").attr("aria-expanded","true");
    }
  };

  var expandLevel = function(e){
    var $expander = $(this);
    var group = $(this).data('more');
    var text;
    if($expander.hasClass('in')){
      $('.'+group).show();
      text = $expander.text();
      $expander.text($expander.data('text')).removeClass('in');
      $expander.data('text',text);

    } else {
      $('.'+group).hide();
      text = $expander.text();
      $expander.text($expander.data('text')).addClass('in');  
      $expander.data('text',text);
    }
    
  };

  var showMobile = function(e){
    var $filters = $('#filter-form');
    if($filters.hasClass('open')){
      
     
      $filters.css('-webkit-transition', 'all 300ms ease-in-out');
      setTimeout(function(){
        $filters.removeAttr('style');
      }, 300);
      
      $filters.removeClass('open');
      $('body').removeClass('hp-filter-open');
    } else {
      $filters.addClass('open');
      $('body').addClass('hp-filter-open');
    }
  };

  var submitFilters = function(e){
    var url = "#"; // the script where you handle the form input.
    //do not uncomment - Richa $('#loading-results').show();
    var $filterList = $('.applied-filters');
    var $filterClear = $('#filter-clear');
    //var $scf = $('#scf');
    $filterList.find('li, ul').remove();
    //$('#scf li').remove('li');
    var numFilters = 0;
    //var $clearButton = $(document.createElement('button')).addClass('applied-filters-item').attr('data-filter','clear');
    $('.filter-options input[type="checkbox"]').not('[data-filter="all"]').each(function(){
      var $input = $(this);
      if($input.prop('checked')){
        var $tag = $(document.createElement('li'));
        var $button = $(document.createElement('button'));
        var parentTitle = $(this).parents('.filter-category').children('.filter-title').html();
        var title;
        var categoryList;
        //var $top;
        $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-filters-item').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('data-selected-title',parentTitle).append(title).append($tag);
          $filterList.append(categoryList);
        }
        SCF.initElem($tag);
        //Adding filter on top
        //$top = $tag.clone().removeClass('hidden-lg');
        //$scf.append($top.removeClass('hidden-lg')[0]);
        //SCF.initElem($top);
        numFilters += 1;
      }
      if(numFilters === 0){
        $('#filter-badge').text('');
        //$scf.next().hide().css('visibility', 'hidden');  
      } else {
        $('#filter-badge').text(numFilters);
        //$scf.next().show().css('visibility', 'visible');
      }
    });
    $('#filter-trigger span').remove();
    if (numFilters > 0){
      $filterList.show();
      $('#filter-trigger').append('<span> ('+ numFilters +')</span>');
      $('#filter-title').css('display','inline');
    }
    else {
      $filterList.hide();
      $('#filter-title').hide();
      $('#filter-trigger').remove('span');
    }
    if (numFilters >= 3) {
      $filterClear.show();
    }
    else {
      $filterClear.hide();
    }
  /*do not uncomment - Richa  setTimeout(function(){
      $.ajax({
       type: "POST",
       url: url,
       data: $("#filter-form").serialize(), // serializes the form's elements.
       success: function(data)
       {
          $('#loading-results').hide();
       },
       error: function(data){
          $('#loading-results').hide();
       }
     });
    }, 1000); */
    return false;
  };
  var clearFilters = function(e){
    e.preventDefault();
    var $inputs = $('.filter-options input[type="checkbox"]');
    $('.applied-filters li').remove();
    $inputs.not('[data-filter="all"]').icheck('unchecked');
    var $all = $('[data-filter="all"]');
    $all.attr('checked', 'checked').parent('label').addClass('selected');
    applyFilter();
  };
  var clearSiblingFilters = function(e){
    var $all = $(this);
    if($all.attr('checked')){
      var $inputs = $all.parents('.filter-options').find('input[type="checkbox"]');
      $inputs.not($all).icheck('unchecked');
      applyFilter();
    }
  };
	return {
		init: init
	};
}());

}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{//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
	};
})();
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{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
    };
}());
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{// 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.ajax-select').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('.fancy-select').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('.fancy-select').show().addClass('last');
	          	$form.find('.select-loader').hide();
	          } else {
	          	$form.find('.select-loader').hide();
	          	$('.troubleshoot-results').show();
	          }
	       }
	     });
	    }, 1000);
	    return false;
	};

	return {
		init: init
	};
}());

}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{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
    };
}());
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{// 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 = $('#oneboxtextsearch.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
    };
}());
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{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
	};
}());
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{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-choose-language').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('modal-xl').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('modal-sm').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
	};
}());
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{PSF = (function(){

	var $window;
	var $footer;
	var $psf;
	var psfHeight;

	var init = function(){
		if($('#psf').length){
			$window = $(window);
			$footer = $('#footer');
			$psf = $('#psf');
			psfHeight = $('#psf').height();
			addHandlers();
			//$('#notifications-trigger').trigger('click');  //Please do not 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';
	    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 = $('.notifications-bg').find('.notification').size();
		$('#totalNotifications').text(totalNotifications);
	};

	countNotifications();

	// Open notifications on click
	$('#notifications-trigger').on('tap click', function(e) {
		e.preventDefault();
		$('.notifications-bg').addClass('open');
		$(this).toggleClass('open');
		$("#dismiss-notifications").attr("aria-hidden","false");
	});

	// 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('icon-rght').addClass('icon-lft');
		} else {
			$('#psf-gripper .icon').removeClass('icon-lft').addClass('icon-rght');
			//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
	};
}());
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{// 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 = $('#oneboxtextsearch');

    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 .hp-search').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(".search-bg").find("#search-dropdown").innerWidth() + 15;
             $(this).siblings(".typeaheadHook").val(typeaheadLeftHookDesktop);
             $(this).css("padding-left",typeaheadLeftHookDesktop);

            
             $(this).parents(".search-bg").find("#search-dropdown").innerWidth() + 15;
             isDesktop=true;
             $(this).unbind("blur");
             handleGhostScript(jQuery(this));
        	$(this).on("blur",function(){
        		$(this).trigger("blurTypeahead");
        	})
        });
        
       
        
       // do not uncomment - Varun $('.hp-header #oneboxtextsearch').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 _hp-structure.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")
	           
           isDesktop = false;
            $(this).unbind("blur");
            handleGhostScript(jQuery(this));
            $(this).on("blur",function(){
        		$(this).trigger("blurTypeahead");
        	})
       	 }
       });
        
      // do not uncomment - Varun $('.hp-header #oneboxtextsearch').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 #oneboxtextsearch').val($('.hp-header #oneboxtextsearch').attr("ghosttext"));
      $('.hp-header #oneboxtextsearch').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
    };

}();
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{/*
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" || activelink == "shop"){
			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-lg-16>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+product-info+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{
			
				currentTab = $('[data-toggle=tab]:visible').first();
				currentTab.attr({"tabindex" : "0"});
			}


			
			/*if(urllocation.indexOf('?')>0){
				
				var urlSplit = identifyActiveTab.split('?');
				currentTab = $("#"+urlSplit[0]);
				
				//currentTab = urllocation[urllocation.length - 1];
				if(tabString.indexof(currentTab)>0){
					currentTab = $("#"+urllocation[urllocation.length - 1]);
					
				}
				
			}
			else{
				currentTab =  $("#findSolutions");
			}*/


		return currentTab;
	}

	return {
		init: init
	}
}());

/*$(document).ready(function(){
	handleAccessibility();
	function handleAccessibility(){
	var indexValue = $(".nav.nav-tabs.hp-nav-tabs li").filter(".active").index();
	$(".hp-nav-tabs a[data-toggle='tab']").each(function(){

			if(typeof ($(this).attr("tabindex")) === 'undefined' && ($(".hp-nav-tabs li").index($(this).parent())<indexValue)){
				$(this).attr("tabindex","0");
			}
			else {
				$(this).attr("tabindex","-1");
			}

	});
	$(".tab-pane").on("focusout",function(e){
		$(this).attr("tabindex", "-1");
		var nextElement = $(".hp-nav-tabs li.active").next();
			while($(nextElement).find("a[data-toggle='tab']").css("display") == "none"){
				nextElement = $(nextElement).next();
			}
		$(nextElement).find("a[data-toggle='tab']").attr("tabindex","0"); 
		$(nextElement).find("a[data-toggle='tab']").focus();
		$(".tab-pane").find("a").attr("tabindex","-1");
	});
	$(".hp-nav-tabs a[data-toggle='tab']").on("focusout",function(e){
		if($(this).parent().hasClass("active")){
			return;
		}
		$(this).parent().next().find("a[data-toggle='tab']").attr("tabindex","0");
		$(this).parent().next().find("a[data-toggle='tab']").focus();
	});
}

	$(".hp-nav-tabs a[data-toggle='tab']").on("keydown keypress keyup",function(e){
		var keycode = e.keycode || e.which;
		if(keycode == 13){
			handleAccessibility();
		}
	});


/*	$(".hp-nav-tabs a[data-toggle='tab']").on("keydown keypress keyup",function(e){
		var keyCode = e.keyCode || e.which; 

  		if (keyCode == 9) { 
			var nextElement = $(".hp-nav-tabs li.active").next();
			while($(nextElement).find("a[data-toggle='tab']").css("display") == "none"){
				nextElement = $(nextElement).next();
			}
			$(nextElement).find("a[data-toggle='tab']").attr("tabindex","0"); 
		}
	});
});
*/ //Do not remove the comment //Pratisha
/*	$("body").on('keydown keypress keyup', ".nav.nav-tabs.hp-nav-tabs .active", function(e) { 
	
  	var keyCode = e.keyCode || e.which; 

  	if (keyCode == 9) { 
	if($(".tab-pane.hp-row.fade.active").length > 0){
    /*e.preventDefault(); 
    // call custom function here
    $(".tab-pane.hp-row.fade.active").attr({"tabindex":"0","aria-expanded":true});
	}
	else{
		return false;
	}
  } 
});*/
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{Guided = (function(){
	var step = 1;
	var step11state = 1;
	var timeout;
	var init = function(){
		if($('#guided').length){

			addHandlers();
		}
		stepsLabel();
	};

	var addHandlers = function(){
		$('#step-1 .guided-action').on('click', showNext);
		$('#step-2 .guided-action').on('click', showStep3);
		$('#step-3 .product-selection a').on('click', showLoading);
		$('.steptrigger').on('click', triggerState);
		$('#step-3 .re-scan').on('click', resetStep3);
		$('#step-5 .download-list .button').on('click', showNext);
		$('#step-5 input').on('change', handleUncheck);
		$('#step-7 .guided-action').on('click', showProgressBar);
		$('#step-9 .guided-action').on('click', showLoading);
	};

	var triggerState = function(e){
		e.preventDefault();
		var $el = $('.step'+ step + 'rotation:visible');
		$el.addClass('hidden');
		if ($el.next('.step'+ step +'rotation')[0]){
			$el.next().removeClass('hidden');
		}
		else {
			$('.step'+ step +'rotation').first().removeClass('hidden');
		}
		if (step === 11){
			step6state++;

			changeTitle1();

			if (step6state === 3){
				step6state = 1;
			}
		}
	};

	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('button-disabled').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 .product-selection:visible');
				var $found = $('#found-selections .product-selection:visible');
				$('#found-count').html('(' + $found.length+')');
				$('#network-count').html('(' + $network.length+')');
			},finishLoading/4 * (index + 1));
		});
		timeout = setTimeout(function(){
			$('#step-3 .progress-bar-component').hide();
			$('#step-3 .header1').first().addClass('hidden');
			$('#step-3 .header2').first().removeClass('hidden');
			$('#identify-text1').addClass('hidden');
			$('#identify-text2').removeClass('hidden');
		},finishLoading + 500);
	};

	var showLoading = function(e){
		e.preventDefault();
		showNext();
		setTimeout(showNext,4000);
	};

	var showProgressBar = function(){
		window.runProgressBar();
		setTimeout(showNext,6000);
		showNext();
	};
	return {
		init: init
	};
}());
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{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(){
		$('#FindMyDriver').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){
		$("#modal-select-diff-os").hide();
		$("#modal-select-diff-os-nodrivers").hide();
		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
	};
})();
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{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*/
  };

  var swdDropdown = function(ev) {
    if (typeof ev !== "undefined")
        ev.preventDefault();

    if ($(this).hasClass("toggled")) {
        $(this).parents('.swd-dropdown-row').next().remove();
        if (!$(this).parents().hasClass("panel-child")) {
            $(this).parents('.table-responsive').find(".swd-dropdown").removeClass('toggled');
        } else {
            $("#" + $(this).parents('.table-responsive')[0].id).find(".swd-dropdown").removeClass('toggled');
        }
        if ($(this).parents('.table-responsive').hasClass('detail-responsive')) {
            $(this).parents('.table-responsive').removeClass('detail-responsive');
        }
    } else {
        $(this).parents('.swd-dropdown-row').next().remove();
        if (!$(this).parents().hasClass("panel-child")) {
            $(this).parents('.table-responsive').find(".swd-dropdown").removeClass('toggled');
        } else {
            $("#" + $(this).parents('.table-responsive')[0].id).find(".swd-dropdown").removeClass('toggled');
        }
        $(this).addClass('toggled');
        // if($(this).parents('.swd-dropdown-row').next().hasClass('swd-expanded')){
        //     $(this).parents('.swd-dropdown-row').next().remove();
        //     $(this).removeClass('toggled');
        //     $(this).parents('.table-responsive').removeClass('detail-responsive');
        // }

        // else{

        if ($(this).parents('.table-responsive').hasClass('detail-responsive')) {
            $(this).parents('.table-responsive').removeClass('detail-responsive');
        }

        var href = $(this).attr('data-target');
        var el = $(href);
        var element = $(el[0]).clone();
        element.removeClass("collapse");
        var row = $('<tr class="swd-expanded drivers-no-padding"><td colspan="100"></td></tr>');
        //$('#download-table .swd-expanded').remove();  //Commenting for multiple details tab impl.
        /*if ($(this).hasClass('toggled')) {
            $('#download-table .swd-dropdown').removeClass('toggled');
            $("#download-table .table-responsive").removeClass("detail-responsive"); //Adjust space issue
            return;
        }
        $('#download-table .swd-dropdown').removeClass('toggled'); */

        element.appendTo(row.children('td'));
        row.insertAfter($(this).parents('tr').not('.sortable-row'));
        $(this).addClass('toggled');
        if (!mobileDevice) {
            if (typeof SSF != "undefined" && typeof SSF.HPWPD.AttachEventHandlers != "undefined") {
                SSF.HPWPD.AttachEventHandlers();
            } else {
                attachNonHPDIAHandler();
            }
        }
        $('.hpdiaButton').on('click', function(event) {
           	downloadSoftwareId = $(this).attr('softwareid');      
        });
        $('.hpdiaButtonMbl').on('click', function(event) {
            downloadSoftwareId = $(this).attr('softwareid');
            location.href = $(this).attr('downloadUrl');
        });
        /* To adjust space issue below detailsTab :Sushmita */
        $("#download-table .table-responsive").removeClass("detail-responsive");
        $(".swd-expanded").parents("#download-table .table-responsive").addClass("detail-responsive");

        /* End: To adjust space issue below detailsTab :Sushmita */
        // }
    }

};

var featuredDriverShow = function(ev) {
    if (typeof ev !== "undefined")
        ev.preventDefault();

    var detailsAnchorEl = $(this).parents(".panel").find(".featuredDriver");
    if (detailsAnchorEl.length > 0) {
        if (!($(this).hasClass("basicTitle"))) {
            if (!($(this).hasClass("toggled"))) {
                swdDropdown.call(detailsAnchorEl);
            } else {
                detailsAnchorEl.removeClass("toggled");
            }
        }
    }

};

  /* 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-sort-trigger]').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;
			});
			$sortEls = $(sortEls).map(function(index){
				return $(this).parents('.sortable-row')[0];
			});
			console.log($(this).find('.table > tbody'));
			console.log($sortEls);
			$(this).find('.table > tbody').html($sortEls);
		});
		$this.toggleClass('reverse');
		$('.swd-dropdown').on('click', swdDropdown);
	};
	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
    
  };
}());
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{$(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;
  });
});
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{/* ========================================================================
 * 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 = $('<div class="modal-backdrop ' + animate + '" />')
        .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('modal-open') })
    .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open') })

}(jQuery);

}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{/* ========================================================================
 * 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' : 'webkitTransitionEnd'
    , 'MozTransition'    : 'transitionend'
    , 'OTransition'      : 'oTransitionEnd otransitionend'
    , 'transition'       : 'transitionend'
    }

    for (var name in transEndEventNames) {
      if (el.style[name] !== undefined) {
        return { end: transEndEventNames[name] }
      }
    }
  }

  // http://blog.alexmaccaw.com/css-transitions
  $.fn.emulateTransitionEnd = function (duration) {
    var called = false, $el = this
    $(this).one($.support.transition.end, function () { called = true })
    var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
    setTimeout(callback, duration)
    return this
  }

  $(function () {
    $.support.transition = transitionEnd()
  })

}(jQuery);

}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{// Generated by CoffeeScript 1.4.0
(function() {


  $ = window.jQuery || window.Zepto || window.$;

  $.fn.fancySelect = function(opts) {
    var isiOS, settings;
    if (opts == null) {
      opts = {};
    }
    settings = $.extend({
      forceiOS: false,
      includeBlank: false,
      optionTemplate: function(optionEl) {
        return optionEl.text();
      },
      triggerTemplate: function(optionEl) {
        return optionEl.text();
      }
    }, opts);
    isiOS = !!navigator.userAgent.match(/iP(hone|od|ad)/i);
    return this.each(function() {
      var copyOptionsToList, disabled, options, sel, trigger, updateTriggerText, wrapper;
      sel = $(this);
      if (sel.hasClass('fancified') || sel[0].tagName !== 'SELECT') {
        return;
      }

      /*
       * @author TYPOWORX <info@typoworx.de>
       * Add close on body-click
      */
      $('body').on('click', function(e) {
        if($('.fancy-select > .trigger').is('.open')) {
          if(!$(e.target).is('.trigger') && $(e.target).closest('.fancy-select > .trigger').length == 0) {
            trigger.trigger('close.fs');
          }
        }
      });

      sel.addClass('fancified');
      sel.css({
        width: 1,
        height: 1,
        display: 'block',
        position: 'absolute',
        top: 0,
        left: 0,
        opacity: 0
      });
      sel.wrap('<div class="fancy-select">');
      wrapper = sel.parent();
      if (sel.data('class')) {
        wrapper.addClass(sel.data('class'));
      }
      wrapper.append('<div class="trigger">');
      if (!(isiOS && !settings.forceiOS)) {
        wrapper.append('<ul class="options">');
      }
      trigger = wrapper.find('.trigger');
      options = wrapper.find('.options');
      disabled = sel.prop('disabled');
      if (disabled) {
        wrapper.addClass('disabled');
      }
      updateTriggerText = function() {
        var triggerHtml;
        triggerHtml = settings.triggerTemplate(sel.find(':selected'));
        return trigger.html(triggerHtml);
      };
      sel.on('blur.fs', function() {
        if (trigger.hasClass('open')) {
          return setTimeout(function() {
            return trigger.trigger('close.fs');
          }, 120);
        }
      });
      trigger.on('close.fs', function() {
        trigger.removeClass('open');
        return options.removeClass('open');
      });
      trigger.on('click.fs', function() {
        var offParent, parent;
        if (!disabled) {
          trigger.toggleClass('open');
          if (isiOS && !settings.forceiOS) {
            if (trigger.hasClass('open')) {
              return sel.focus();
            }
          } else {
            if (trigger.hasClass('open')) {
              parent = trigger.parent();
              offParent = parent.offsetParent();
              if ((parent.offset().top + parent.outerHeight() + options.outerHeight() + 20) > $(window).height() + $(window).scrollTop()) {
                options.addClass('overflowing');
              } else {
                options.removeClass('overflowing');
              }
            }
            options.toggleClass('open');

            /*
             * @author TYPOWORX <info@typoworx.de>
             * Bugfix, don't use will close on scroll!
            */
            //if (!isiOS) {
            //  return sel.focus();
            //}
          }
        }
      });
      sel.on('enable', function() {
        sel.prop('disabled', false);
        wrapper.removeClass('disabled');
        disabled = false;
        return copyOptionsToList();
      });
      sel.on('disable', function() {
        sel.prop('disabled', true);
        wrapper.addClass('disabled');
        return disabled = true;
      });
      sel.on('change.fs', function(e) {
        if (e.originalEvent && e.originalEvent.isTrusted) {
          return e.stopPropagation();
        } else {
          return updateTriggerText();
        }
      });
      sel.on('keydown', function(e) {
        var hovered, newHovered, w;
        w = e.which;
        hovered = options.find('.hover');
        hovered.removeClass('hover');
        if (!options.hasClass('open')) {
          if (w === 13 || w === 32 || w === 38 || w === 40) {
            e.preventDefault();
            return trigger.trigger('click.fs');
          }
        } else {
          if (w === 38) {
            e.preventDefault();
            if (hovered.length && hovered.index() > 0) {
              hovered.prev().addClass('hover');
            } else {
              options.find('li:last-child').addClass('hover');
            }
          } else if (w === 40) {
            e.preventDefault();
            if (hovered.length && hovered.index() < options.find('li').length - 1) {
              hovered.next().addClass('hover');
            } else {
              options.find('li:first-child').addClass('hover');
            }
          } else if (w === 27) {
            e.preventDefault();
            trigger.trigger('click.fs');
          } else if (w === 13 || w === 32) {
            e.preventDefault();
            hovered.trigger('click.fs');
          } else if (w === 9) {
            if (trigger.hasClass('open')) {
              trigger.trigger('close.fs');
            }
          }
          newHovered = options.find('.hover');
          if (newHovered.length) {
            options.scrollTop(0);
            return options.scrollTop(newHovered.position().top - 12);
          }
        }
      });
      options.on('click.fs', 'li', function(e) {
        var clicked;
        clicked = $(this);
        sel.val(clicked.data('raw-value'));
        if (!isiOS) {
          sel.trigger('blur.fs').trigger('focus.fs');
        }
        options.find('.selected').removeClass('selected');
        clicked.addClass('selected');
        return sel.val(clicked.data('raw-value')).trigger('change.fs').trigger('blur.fs').trigger('focus.fs');
      });
      options.on('mouseenter.fs', 'li', function() {
        var hovered, nowHovered;
        nowHovered = $(this);
        hovered = options.find('.hover');
        hovered.removeClass('hover');
        return nowHovered.addClass('hover');
      });
      options.on('mouseleave.fs', 'li', function() {
        return options.find('.hover').removeClass('hover');
      });
      copyOptionsToList = function() {
        var selOpts;
        updateTriggerText();
        if (isiOS && !settings.forceiOS) {
          return;
        }
        selOpts = sel.find('option');
        return sel.find('option').each(function(i, opt) {
          var optHtml;
          opt = $(opt);
          if (!opt.prop('disabled') && (opt.val() || settings.includeBlank)) {
            optHtml = settings.optionTemplate(opt);
            if (opt.prop('selected')) {
              return options.append("<li data-raw-value=\"" + (opt.val()) + "\" class=\"selected\">" + optHtml + "</li>");
            } else {
              return options.append("<li data-raw-value=\"" + (opt.val()) + "\">" + optHtml + "</li>");
            }
          }
        });
      };
      sel.on('update.fs', function() {
        wrapper.find('.options').empty();
        return copyOptionsToList();
      });
      return copyOptionsToList();
    });
  };

}).call(this);
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{/**
*
* Version: 0.0.8
* Author: Gianluca Guarini
* Contact: gianluca.guarini@gmail.com
* 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)
					}
				});
			}
		}
	});
	setListener(doc, isTouch ? 'touchmove' : 'mousemove', function(e) {
		var pointer = getPointerEvent(e);
		currX = pointer.pageX;
		currY = pointer.pageY;
	});
}(document, window));
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{/* ========================================================================
 * 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: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
  , trigger: 'hover focus'
  , title: ''
  , delay: 0
  , html: false
  , container: false
  }

  Tooltip.prototype.init = function (type, element, options) {
    this.enabled  = true
    this.type     = type
    this.$element = $(element)
    this.options  = this.getOptions(options)

    var triggers = this.options.trigger.split(' ')

    for (var i = triggers.length; i--;) {
      var trigger = triggers[i]

      if (trigger == 'click') {
        this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
      } else if (trigger != 'manual') {
        var eventIn  = trigger == 'hover' ? 'mouseenter' : 'focus'
        var eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'

        this.$element.on(eventIn  + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
        this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
      }
    }

    this.options.selector ?
      (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
      this.fixTitle()
  }

  Tooltip.prototype.getDefaults = function () {
    return Tooltip.DEFAULTS
  }

  Tooltip.prototype.getOptions = function (options) {
    options = $.extend({}, this.getDefaults(), this.$element.data(), options)

    if (options.delay && typeof options.delay == 'number') {
      options.delay = {
        show: options.delay
      , hide: options.delay
      }
    }

    return options
  }

  Tooltip.prototype.getDelegateOptions = function () {
    var options  = {}
    var defaults = this.getDefaults()

    this._options && $.each(this._options, function (key, value) {
      if (defaults[key] != value) options[key] = value
    })

    return options
  }

  Tooltip.prototype.enter = function (obj) {
    var self = obj instanceof this.constructor ?
      obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)

    clearTimeout(self.timeout)

    self.hoverState = 'in'

    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 = placement
        var docScroll    = document.documentElement.scrollTop || document.body.scrollTop
        var parentWidth  = this.options.container == 'body' ? window.innerWidth  : $parent.outerWidth()
        var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight()
        var parentLeft   = this.options.container == 'body' ? 0 : $parent.offset().left

        placement = placement == 'bottom' && pos.top   + pos.height  + actualHeight - docScroll > parentHeight  ? 'top'    :
                    placement == 'top'    && pos.top   - docScroll   - actualHeight < 0                         ? 'bottom' :
                    placement == 'right'  && pos.right + actualWidth > parentWidth                              ? 'left'   :
                    placement == 'left'   && pos.left  - actualWidth < parentLeft                               ? 'right'  :
                    placement

        $tip
          .removeClass(orgPlacement)
          .addClass(placement)
      }

      var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)

      this.applyPlacement(calculatedOffset, placement)
      this.$element.trigger('shown.bs.' + this.type)
    }
  }

  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

    if (placement == 'top' && actualHeight != height) {
      replace = true
      offset.top = offset.top + height - actualHeight
    }

    if (/bottom|top/.test(placement)) {
      var delta = 0

      if (offset.left < 0) {
        delta       = offset.left * -2
        offset.left = 0

        $tip.offset(offset)

        actualWidth  = $tip[0].offsetWidth
        actualHeight = $tip[0].offsetHeight
      }

      this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
    } else {
      this.replaceArrow(actualHeight - height, actualHeight, 'top')
    }

    if (replace) $tip.offset(offset)
  }

  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()

    this.$element.trigger('hidden.bs.' + this.type)

    return this
  }

  Tooltip.prototype.fixTitle = function () {
    var $e = this.$element
    if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
      $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
    }
  }

  Tooltip.prototype.hasContent = function () {
    return this.getTitle()
  }

  Tooltip.prototype.getPosition = function () {
    var el = this.$element[0]
    return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
      width: el.offsetWidth
    , height: el.offsetHeight
    }, this.$element.offset())
  }

  Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
    return placement == 'bottom' ? { top: pos.top + pos.height,   left: pos.left + pos.width / 2 - actualWidth / 2  } :
           placement == 'top'    ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2  } :
           placement == 'left'   ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
        /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width   }
  }

  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) {
      this.hide()
      this.$element = null
      this.options  = null
    }
  }

  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);

}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{/**
* 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
            $elements.each(function() {
                var $that = $(this),
                    display = $that.css('display') === 'inline-block' ? 'inline-block' : 'block';

                $that.css({
                    'display': display,
                    'padding-top': '0',
                    'padding-bottom': '0',
                    'border-top-width': '0',
                    'border-bottom-width': '0',
                    'height': '100px'
                });
            });

            // get the array of rows (based on element top position)
            rows = _rows($elements);

            // revert the temporary forced style
            $elements.css({
                'display': '',
                'padding-top': '',
                'padding-bottom': '',
                'border-top-width': '',
                'border-bottom-width': '',
                'height': ''
            });
        }

        $.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' ? 'inline-block' : '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
                $that.css({ 'display': '' });
            });

            // 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 border-box)
                if ($that.css('box-sizing') !== 'border-box') {
                    verticalPadding += _parse($that.css('border-top-width')) + _parse($that.css('border-bottom-width'));
                    verticalPadding += _parse($that.css('padding-top')) + _parse($that.css('padding-bottom'));
                }

                // 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-match-height 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);
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{/*!
 * 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);
	};

}));
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{/*!
 * jQuery.scrollTo
 * Copyright (c) 2007-2014 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com
 * Licensed under MIT
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * @projectDescription Easy element scrolling using jQuery.
 * @author Ariel Flesler
 * @version 1.4.13
 */
;(function (define) {
	'use strict';

	define(['jquery'], function ($) {

		var $scrollTo = $.scrollTo = function( target, duration, settings ) {
			return $(window).scrollTo( target, duration, settings );
		};

		$scrollTo.defaults = {
			axis:'xy',
			duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1,
			limit:true
		};

		// Returns the element that needs to be animated to scroll the window.
		// Kept for backwards compatibility (specially for localScroll & serialScroll)
		$scrollTo.window = function( scope ) {
			return $(window)._scrollable();
		};

		// Hack, hack, hack :)
		// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
		$.fn._scrollable = function() {
			return this.map(function() {
				var elem = this,
					isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

					if (!isWin)
						return elem;

				var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;

				return /webkit/i.test(navigator.userAgent) || doc.compatMode == 'BackCompat' ?
					doc.body :
					doc.documentElement;
			});
		};

		$.fn.scrollTo = function( target, duration, settings ) {
			if (typeof duration == 'object') {
				settings = duration;
				duration = 0;
			}
			if (typeof settings == 'function')
				settings = { onAfter:settings };

			if (target == 'max')
				target = 9e9;

			settings = $.extend( {}, $scrollTo.defaults, settings );
			// Speed is still recognized for backwards compatibility
			duration = duration || settings.duration;
			// Make sure the settings are given right
			settings.queue = settings.queue && settings.axis.length > 1;

			if (settings.queue)
				// Let's keep the overall duration
				duration /= 2;
			settings.offset = both( settings.offset );
			settings.over = both( settings.over );

			return this._scrollable().each(function() {
				// Null target yields nothing, just like jQuery does
				if (target == null) return;

				var elem = this,
					$elem = $(elem),
					targ = target, toff, attr = {},
					win = $elem.is('html,body');

				switch (typeof targ) {
					// A number will pass the regex
					case 'number':
					case 'string':
						if (/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(targ)) {
							targ = both( targ );
							// We are done
							break;
						}
						// Relative/Absolute selector, no break!
						targ = win ? $(targ) : $(targ, this);
						if (!targ.length) return;
					case 'object':
						// DOMElement / jQuery
						if (targ.is || targ.style)
							// Get the real position of the target
							toff = (targ = $(targ)).offset();
				}

				var offset = $.isFunction(settings.offset) && settings.offset(elem, targ) || settings.offset;

				$.each( settings.axis.split(''), function( i, axis ) {
					var Pos	= axis == 'x' ? 'Left' : 'Top',
						pos = Pos.toLowerCase(),
						key = 'scroll' + Pos,
						old = elem[key],
						max = $scrollTo.max(elem, axis);

					if (toff) {// jQuery / DOMElement
						attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

						// If it's a dom element, reduce the margin
						if (settings.margin) {
							attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
							attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
						}

						attr[key] += offset[pos] || 0;

						if(settings.over[pos])
							// Scroll to a fraction of its width/height
							attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
					} else {
						var val = targ[pos];
						// Handle percentage values
						attr[key] = val.slice && val.slice(-1) == '%' ?
							parseFloat(val) / 100 * max
							: val;
					}

					// Number or 'number'
					if (settings.limit && /^\d+$/.test(attr[key]))
						// Check the limits
						attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );

					// Queueing axes
					if (!i && settings.queue) {
						// Don't waste time animating, if there's no need.
						if (old != attr[key])
							// Intermediate animation
							animate( settings.onAfterFirst );
						// Don't animate this axis again in the next iteration.
						delete attr[key];
					}
				});

				animate( settings.onAfter );

				function animate( callback ) {
					$elem.animate( attr, duration, settings.easing, callback && function() {
						callback.call(this, targ, settings);
					});
				}
			}).end();
		};

		// Max scrolling position, works on quirks mode
		// It only fails (not too badly) on IE, quirks mode.
		$scrollTo.max = function( elem, axis ) {
			var Dim = axis == 'x' ? 'Width' : 'Height',
				scroll = 'scroll'+Dim;

			if (!$(elem).is('html,body'))
				return elem[scroll] - $(elem)[Dim.toLowerCase()]();

			var size = 'client' + Dim,
				html = elem.ownerDocument.documentElement,
				body = elem.ownerDocument.body;

			return Math.max( html[scroll], body[scroll] ) - Math.min( html[size]  , body[size]   );
		};

		function both( val ) {
			return $.isFunction(val) || typeof val == 'object' ? val : { top:val, left:val };
		}

		// AMD requirement
		return $scrollTo;
	})
}(typeof define === 'function' && define.amd ? define : function (deps, factory) {
	if (typeof module !== 'undefined' && module.exports) {
		// Node
		module.exports = factory(require('jquery'));
	} else {
		factory(jQuery);
	}
}));

}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{/* ========================================================================
 * Bootstrap: popover.js v3.0.2
 * http://getbootstrap.com/javascript/#popovers
 * ========================================================================
 * 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";

  // POPOVER PUBLIC CLASS DEFINITION
  // ===============================

  var Popover = function (element, options) {
    this.init('popover', element, options)
  }

  if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')

  Popover.DEFAULTS = $.extend({} , $.fn.tooltip.Constructor.DEFAULTS, {
    placement: 'right'
  , trigger: 'click'
  , content: ''
  , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
  })


  // NOTE: POPOVER EXTENDS tooltip.js
  // ================================

  Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)

  Popover.prototype.constructor = Popover

  Popover.prototype.getDefaults = function () {
    return Popover.DEFAULTS
  }

  Popover.prototype.setContent = function () {
    var $tip    = this.tip()
    var title   = this.getTitle()
    var content = this.getContent()

    $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
    $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content)

    $tip.removeClass('fade top bottom left right in')

    // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
    // this manually by checking the contents.
    if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
  }

  Popover.prototype.hasContent = function () {
    return this.getTitle() || this.getContent()
  }

  Popover.prototype.getContent = function () {
    var $e = this.$element
    var o  = this.options

    return $e.attr('data-content')
      || (typeof o.content == 'function' ?
            o.content.call($e[0]) :
            o.content)
  }

  Popover.prototype.arrow = function () {
    return this.$arrow = this.$arrow || this.tip().find('.arrow')
  }

  Popover.prototype.tip = function () {
    if (!this.$tip) this.$tip = $(this.options.template)
    return this.$tip
  }


  // POPOVER PLUGIN DEFINITION
  // =========================

  var old = $.fn.popover

  $.fn.popover = function (option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.popover')
      var options = typeof option == 'object' && option

      if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.popover.Constructor = Popover


  // POPOVER NO CONFLICT
  // ===================

  $.fn.popover.noConflict = function () {
    $.fn.popover = old
    return this
  }

}(jQuery);

}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{/*!

Holder - client side image placeholders
Version 2.4.0+bxlim
© 2014 Ivan Malopinsky - http://imsky.co

Site:     http://imsky.github.io/holder
Issues:   https://github.com/imsky/holder/issues
License:  http://opensource.org/licenses/MIT

*/
!function(e,t,r){t[e]=r}("onDomReady",this,function(e){"use strict";function t(e){if(!b){if(!a.body)return i(t);for(b=!0;e=S.shift();)i(e)}}function r(e){(y||e.type===s||a[c]===u)&&(n(),t())}function n(){y?(a[x](m,r,d),e[x](s,r,d)):(a[g](v,r),e[g](h,r))}function i(e,t){setTimeout(e,+t>=0?t:1)}function o(e){b?i(e):S.push(e)}null==document.readyState&&document.addEventListener&&(document.addEventListener("DOMContentLoaded",function E(){document.removeEventListener("DOMContentLoaded",E,!1),document.readyState="complete"},!1),document.readyState="loading");var a=e.document,l=a.documentElement,s="load",d=!1,h="on"+s,u="complete",c="readyState",f="attachEvent",g="detachEvent",p="addEventListener",m="DOMContentLoaded",v="onreadystatechange",x="removeEventListener",y=p in a,w=d,b=d,S=[];if(a[c]===u)i(t);else if(y)a[p](m,r,d),e[p](s,r,d);else{a[f](v,r),e[f](h,r);try{w=null==e.frameElement&&l}catch(C){}w&&w.doScroll&&!function k(){if(!b){try{w.doScroll("left")}catch(e){return i(k,50)}n(),t()}}()}return o.version="1.4.0",o.isReady=function(){return b},o}(this)),document.querySelectorAll||(document.querySelectorAll=function(e){var t,r=document.createElement("style"),n=[];for(document.documentElement.firstChild.appendChild(r),document._qsa=[],r.styleSheet.cssText=e+"{x-qsa:expression(document._qsa && document._qsa.push(this))}",window.scrollBy(0,0),r.parentNode.removeChild(r);document._qsa.length;)t=document._qsa.shift(),t.style.removeAttribute("x-qsa"),n.push(t);return document._qsa=null,n}),document.querySelector||(document.querySelector=function(e){var t=document.querySelectorAll(e);return t.length?t[0]:null}),document.getElementsByClassName||(document.getElementsByClassName=function(e){return e=String(e).replace(/^|\s+/g,"."),document.querySelectorAll(e)}),Object.keys||(Object.keys=function(e){if(e!==Object(e))throw TypeError("Object.keys called on non-object");var t,r=[];for(t in e)Object.prototype.hasOwnProperty.call(e,t)&&r.push(t);return r}),function(e){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.atob=e.atob||function(e){e=String(e);var r,n=0,i=[],o=0,a=0;if(e=e.replace(/\s/g,""),e.length%4===0&&(e=e.replace(/=+$/,"")),e.length%4===1)throw Error("InvalidCharacterError");if(/[^+/0-9A-Za-z]/.test(e))throw Error("InvalidCharacterError");for(;n<e.length;)r=t.indexOf(e.charAt(n)),o=o<<6|r,a+=6,24===a&&(i.push(String.fromCharCode(o>>16&255)),i.push(String.fromCharCode(o>>8&255)),i.push(String.fromCharCode(255&o)),a=0,o=0),n+=1;return 12===a?(o>>=4,i.push(String.fromCharCode(255&o))):18===a&&(o>>=2,i.push(String.fromCharCode(o>>8&255)),i.push(String.fromCharCode(255&o))),i.join("")},e.btoa=e.btoa||function(e){e=String(e);var r,n,i,o,a,l,s,d=0,h=[];if(/[^\x00-\xFF]/.test(e))throw Error("InvalidCharacterError");for(;d<e.length;)r=e.charCodeAt(d++),n=e.charCodeAt(d++),i=e.charCodeAt(d++),o=r>>2,a=(3&r)<<4|n>>4,l=(15&n)<<2|i>>6,s=63&i,d===e.length+2?(l=64,s=64):d===e.length+1&&(s=64),h.push(t.charAt(o),t.charAt(a),t.charAt(l),t.charAt(s));return h.join("")}}(this),function(){function e(t,r,n){t.document;var i,o=t.currentStyle[r].match(/([\d\.]+)(%|cm|em|in|mm|pc|pt|)/)||[0,0,""],a=o[1],l=o[2];return n=n?/%|em/.test(l)&&t.parentElement?e(t.parentElement,"fontSize",null):16:n,i="fontSize"==r?n:/width/i.test(r)?t.clientWidth:t.clientHeight,"%"==l?a/100*i:"cm"==l?.3937*a*96:"em"==l?a*n:"in"==l?96*a:"mm"==l?.3937*a*96/10:"pc"==l?12*a*96/72:"pt"==l?96*a/72:a}function t(e,t){var r="border"==t?"Width":"",n=t+"Top"+r,i=t+"Right"+r,o=t+"Bottom"+r,a=t+"Left"+r;e[t]=(e[n]==e[i]&&e[n]==e[o]&&e[n]==e[a]?[e[n]]:e[n]==e[o]&&e[a]==e[i]?[e[n],e[i]]:e[a]==e[i]?[e[n],e[i],e[o]]:[e[n],e[i],e[o],e[a]]).join(" ")}function r(r){var n,i=this,o=r.currentStyle,a=e(r,"fontSize"),l=function(e){return"-"+e.toLowerCase()};for(n in o)if(Array.prototype.push.call(i,"styleFloat"==n?"float":n.replace(/[A-Z]/,l)),"width"==n)i[n]=r.offsetWidth+"px";else if("height"==n)i[n]=r.offsetHeight+"px";else if("styleFloat"==n)i.float=o[n];else if(/margin.|padding.|border.+W/.test(n)&&"auto"!=i[n])i[n]=Math.round(e(r,n,a))+"px";else if(/^outline/.test(n))try{i[n]=o[n]}catch(s){i.outlineColor=o.color,i.outlineStyle=i.outlineStyle||"none",i.outlineWidth=i.outlineWidth||"0px",i.outline=[i.outlineColor,i.outlineWidth,i.outlineStyle].join(" ")}else i[n]=o[n];t(i,"margin"),t(i,"padding"),t(i,"border"),i.fontSize=Math.round(a)+"px"}window.getComputedStyle||(r.prototype={constructor:r,getPropertyPriority:function(){throw new Error("NotSupportedError: DOM Exception 9")},getPropertyValue:function(e){return this[e.replace(/-\w/g,function(e){return e[1].toUpperCase()})]},item:function(e){return this[e]},removeProperty:function(){throw new Error("NoModificationAllowedError: DOM Exception 7")},setProperty:function(){throw new Error("NoModificationAllowedError: DOM Exception 7")},getPropertyCSSValue:function(){throw new Error("NotSupportedError: DOM Exception 9")}},window.getComputedStyle=Window.prototype.getComputedStyle=function(e){return new r(e)})}(),Object.prototype.hasOwnProperty||(Object.prototype.hasOwnProperty=function(e){var t=this.__proto__||this.constructor.prototype;return e in this&&(!(e in t)||t[e]!==this[e])}),function(e,t){e.augment=t()}(this,function(){"use strict";var e=function(){},t=Array.prototype.slice,r=function(r,n){var i=e.prototype="function"==typeof r?r.prototype:r,o=new e,a=n.apply(o,t.call(arguments,2).concat(i));if("object"==typeof a)for(var l in a)o[l]=a[l];if(!o.hasOwnProperty("constructor"))return o;var s=o.constructor;return s.prototype=o,s};return r.defclass=function(e){var t=e.constructor;return t.prototype=e,t},r.extend=function(e,t){return r(e,function(e){return this.uber=e,t})},r}),function(e,t){function r(e,t,r,o){var a=n(r.substr(r.lastIndexOf(e.domain)),e);a&&i(null,o,a,t)}function n(e,t){for(var r={theme:p(A.settings.themes.gray,null),stylesheets:t.stylesheets,holderURL:[]},n=!1,i=String.fromCharCode(11),o=e.replace(/([^\\])\//g,"$1"+i).split(i),a=/%[0-9a-f]{2}/gi,l=o.length,s=0;l>s;s++){var d=o[s];if(d.match(a))try{d=decodeURIComponent(d)}catch(h){d=o[s]}var u=!1;if(A.flags.dimensions.match(d))n=!0,r.dimensions=A.flags.dimensions.output(d),u=!0;else if(A.flags.fluid.match(d))n=!0,r.dimensions=A.flags.fluid.output(d),r.fluid=!0,u=!0;else if(A.flags.textmode.match(d))r.textmode=A.flags.textmode.output(d),u=!0;else if(A.flags.colors.match(d)){var c=A.flags.colors.output(d);r.theme=p(r.theme,c),u=!0}else if(t.themes[d])t.themes.hasOwnProperty(d)&&(r.theme=p(t.themes[d],null)),u=!0;else if(A.flags.font.match(d))r.font=A.flags.font.output(d),u=!0;else if(A.flags.auto.match(d))r.auto=!0,u=!0;else if(A.flags.text.match(d))r.text=A.flags.text.output(d),u=!0;else if(A.flags.random.match(d)){null==A.vars.cache.themeKeys&&(A.vars.cache.themeKeys=Object.keys(t.themes));var f=A.vars.cache.themeKeys[0|Math.random()*A.vars.cache.themeKeys.length];r.theme=p(t.themes[f],null),u=!0}u&&r.holderURL.push(d)}return r.holderURL.unshift(t.domain),r.holderURL=r.holderURL.join("/"),n?r:!1}function i(e,t,r,n){var i=r.dimensions,a=r.theme,l=i.width+"x"+i.height;if(e=null==e?r.fluid?"fluid":"image":e,null!=r.text&&(a.text=r.text,"object"===t.nodeName.toLowerCase())){for(var d=a.text.split("\\n"),u=0;u<d.length;u++)d[u]=b(d[u]);a.text=d.join("\\n")}var f=r.holderURL,g=p(n,null);r.font&&(a.font=r.font,!g.noFontFallback&&"img"===t.nodeName.toLowerCase()&&A.setup.supportsCanvas&&"svg"===g.renderer&&(g=p(g,{renderer:"canvas"}))),r.font&&"canvas"==g.renderer&&(g.reRender=!0),"background"==e?null==t.getAttribute("data-background-src")&&c(t,{"data-background-src":f}):c(t,{"data-src":f}),r.theme=a,t.holderData={flags:r,renderSettings:g},("image"==e||"fluid"==e)&&c(t,{alt:a.text?(a.text.length>16?a.text.substring(0,16)+"…":a.text)+" ["+l+"]":l}),"image"==e?("html"!=g.renderer&&r.auto||(t.style.width=i.width+"px",t.style.height=i.height+"px"),"html"==g.renderer?t.style.backgroundColor=a.background:(o(e,{dimensions:i,theme:a,flags:r},t,g),r.textmode&&"exact"==r.textmode&&(A.vars.resizableImages.push(t),s(t)))):"background"==e&&"html"!=g.renderer?o(e,{dimensions:i,theme:a,flags:r},t,g):"fluid"==e&&("%"==i.height.slice(-1)?t.style.height=i.height:null!=r.auto&&r.auto||(t.style.height=i.height+"px"),"%"==i.width.slice(-1)?t.style.width=i.width:null!=r.auto&&r.auto||(t.style.width=i.width+"px"),("inline"==t.style.display||""===t.style.display||"none"==t.style.display)&&(t.style.display="block"),h(t),"html"==g.renderer?t.style.backgroundColor=a.background:(A.vars.resizableImages.push(t),s(t)))}function o(e,t,r,n){function i(){var e=null;switch(n.renderer){case"canvas":e=L(s);break;case"svg":e=O(s,n);break;default:throw"Holder: invalid renderer: "+n.renderer}return e}var o=null;switch(n.renderer){case"svg":if(!A.setup.supportsSVG)return;break;case"canvas":if(!A.setup.supportsCanvas)return;break;default:return}{var l={width:t.dimensions.width,height:t.dimensions.height,theme:t.theme,flags:t.flags},s=a(l);({text:l.text,width:l.width,height:l.height,textHeight:l.font.size,font:l.font.family,fontWeight:l.font.weight,template:l.theme})}if(o=i(),null==o)throw"Holder: couldn't render placeholder";"background"==e?(r.style.backgroundImage="url("+o+")",r.style.backgroundSize=l.width+"px "+l.height+"px"):("img"===r.nodeName.toLowerCase()?c(r,{src:o}):"object"===r.nodeName.toLowerCase()&&(c(r,{data:o}),c(r,{type:"image/svg+xml"})),n.reRender&&setTimeout(function(){var e=i();if(null==e)throw"Holder: couldn't render placeholder";"img"===r.nodeName.toLowerCase()?c(r,{src:e}):"object"===r.nodeName.toLowerCase()&&(c(r,{data:e}),c(r,{type:"image/svg+xml"}))},100)),c(r,{"data-holder-rendered":!0})}function a(e){function t(e,t,r,n){t.width=r,t.height=n,e.width=Math.max(e.width,t.width),e.height+=t.height,e.add(t)}switch(e.font={family:e.theme.font?e.theme.font:"Arial, Helvetica, Open Sans, sans-serif",size:l(e.width,e.height,e.theme.size?e.theme.size:12),weight:e.theme.fontweight?e.theme.fontweight:"bold"},e.text=e.theme.text?e.theme.text:Math.floor(e.width)+"x"+Math.floor(e.height),e.flags.textmode){case"literal":e.text=e.flags.dimensions.width+"x"+e.flags.dimensions.height;break;case"exact":if(!e.flags.exactDimensions)break;e.text=Math.floor(e.flags.exactDimensions.width)+"x"+Math.floor(e.flags.exactDimensions.height)}var r=new F({width:e.width,height:e.height}),n=r.Shape,i=new n.Rect("holderBg",{fill:e.theme.background});i.resize(e.width,e.height),r.root.add(i);var o=new n.Group("holderTextGroup",{text:e.text,align:"center",font:e.font,fill:e.theme.foreground});o.moveTo(null,null,1),r.root.add(o);var a=o.textPositionData=T(r);if(!a)throw"Holder: staging fallback not supported yet.";o.properties.leading=a.boundingBox.height;var s=null,d=null;if(a.lineCount>1){var h=0,u=0,c=e.width*A.setup.lineWrapRatio,f=0;d=new n.Group("line"+f);for(var g=0;g<a.words.length;g++){var p=a.words[g];s=new n.Text(p.text);var m="\\n"==p.text;(h+p.width>=c||m===!0)&&(t(o,d,h,o.properties.leading),h=0,u+=o.properties.leading,f+=1,d=new n.Group("line"+f),d.y=u),m!==!0&&(s.moveTo(h,0),h+=a.spaceWidth+p.width,d.add(s))}t(o,d,h,o.properties.leading);for(var v in o.children)d=o.children[v],d.moveTo((o.width-d.width)/2,null,null);o.moveTo((e.width-o.width)/2,(e.height-o.height)/2,null),(e.height-o.height)/2<0&&o.moveTo(null,0,null)}else s=new n.Text(e.text),d=new n.Group("line0"),d.add(s),o.add(d),o.moveTo((e.width-a.boundingBox.width)/2,(e.height-a.boundingBox.height)/2,null);return r}function l(e,t,r){t=parseInt(t,10),e=parseInt(e,10);var n=Math.max(t,e),i=Math.min(t,e),o=1/12,a=Math.min(.75*i,.75*n*o);return Math.round(Math.max(r,a))}function s(e){var t;t=null==e||null==e.nodeType?A.vars.resizableImages:[e];for(var r in t)if(t.hasOwnProperty(r)){var n=t[r];if(n.holderData){var i=n.holderData.flags,a=d(n,k.invisibleErrorFn(s));if(a){if(i.fluid&&i.auto){var l=n.holderData.fluidConfig;switch(l.mode){case"width":a.height=a.width/l.ratio;break;case"height":a.width=a.height*l.ratio}}var h={dimensions:a,theme:i.theme,flags:i};i.textmode&&"exact"==i.textmode&&(i.exactDimensions=a,h.dimensions=i.dimensions),o("image",h,n,n.holderData.renderSettings)}}}}function d(e,t){var r={height:e.clientHeight,width:e.clientWidth};return r.height||r.width?(e.removeAttribute("data-holder-invisible"),r):(c(e,{"data-holder-invisible":!0}),void t.call(this,e))}function h(e){if(e.holderData){var t=d(e,k.invisibleErrorFn(h));if(t){var r=e.holderData.flags,n={fluidHeight:"%"==r.dimensions.height.slice(-1),fluidWidth:"%"==r.dimensions.width.slice(-1),mode:null,initialDimensions:t};n.fluidWidth&&!n.fluidHeight?(n.mode="width",n.ratio=n.initialDimensions.width/parseFloat(r.dimensions.height)):!n.fluidWidth&&n.fluidHeight&&(n.mode="height",n.ratio=parseFloat(r.dimensions.width)/n.initialDimensions.height),e.holderData.fluidConfig=n}}}function u(e,t){return null==t?E.createElement(e):E.createElementNS(t,e)}function c(e,t){for(var r in t)e.setAttribute(r,t[r])}function f(e,t,r){if(null==e){e=u("svg",C);var n=u("defs",C);e.appendChild(n)}return e.webkitMatchesSelector&&e.setAttribute("xmlns",C),c(e,{width:t,height:r,viewBox:"0 0 "+t+" "+r,preserveAspectRatio:"none"}),e}function g(e,r){if(t.XMLSerializer){{var n=new XMLSerializer,i="",o=r.stylesheets;e.querySelector("defs")}if(r.svgXMLStylesheet){for(var a=(new DOMParser).parseFromString("<xml />","application/xml"),l=o.length-1;l>=0;l--){var s=a.createProcessingInstruction("xml-stylesheet",'href="'+o[l]+'" rel="stylesheet"');a.insertBefore(s,a.firstChild)}var d=a.createProcessingInstruction("xml",'version="1.0" encoding="UTF-8" standalone="yes"');a.insertBefore(d,a.firstChild),a.removeChild(a.documentElement),i=n.serializeToString(a)}var h=n.serializeToString(e);return h=h.replace(/\&amp;(\#[0-9]{2,}\;)/g,"&$1"),i+h}}function p(e,t){var r={};for(var n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);if(null!=t)for(var i in t)t.hasOwnProperty(i)&&(r[i]=t[i]);return r}function m(e){var t=[];for(var r in e)e.hasOwnProperty(r)&&t.push(r+":"+e[r]);return t.join(";")}function v(e){A.vars.debounceTimer||e.call(this),A.vars.debounceTimer&&clearTimeout(A.vars.debounceTimer),A.vars.debounceTimer=setTimeout(function(){A.vars.debounceTimer=null,e.call(this)},A.setup.debounce)}function x(){v(function(){s(null)})}function y(e){var r=null;return"string"==typeof e?r=E.querySelectorAll(e):t.NodeList&&e instanceof t.NodeList?r=e:t.Node&&e instanceof t.Node?r=[e]:t.HTMLCollection&&e instanceof t.HTMLCollection?r=e:null===e&&(r=[]),r}function w(e,t){var r=new Image;r.onerror=function(){t.call(this,!1,e)},r.onload=function(){t.call(this,!0,e)},r.src=e.src}function b(e){for(var t=[],r=0,n=e.length-1;n>=0;n--)r=e[n].charCodeAt(),t.unshift(r>128?["&#",r,";"].join(""):e[n]);return t.join("")}function S(e){return e.replace(/&#(\d+);/g,function(e,t){return String.fromCharCode(t)})}var C="http://www.w3.org/2000/svg",E=t.document,k={addTheme:function(e,t){return null!=e&&null!=t&&(A.settings.themes[e]=t),delete A.vars.cache.themeKeys,this},addImage:function(e,t){var r=E.querySelectorAll(t);if(r.length)for(var n=0,i=r.length;i>n;n++){var o=u("img");c(o,{"data-src":e}),r[n].appendChild(o)}return this},run:function(e){e=e||{};var o={};A.vars.preempted=!0;var a=p(A.settings,e);o.renderer=a.renderer?a.renderer:A.setup.renderer,-1===A.setup.renderers.join(",").indexOf(o.renderer)&&(o.renderer=A.setup.supportsSVG?"svg":A.setup.supportsCanvas?"canvas":"html"),a.use_canvas?o.renderer="canvas":a.use_svg&&(o.renderer="svg");var l=y(a.images),s=y(a.bgnodes),d=y(a.stylenodes),h=y(a.objects);o.stylesheets=[],o.svgXMLStylesheet=!0,o.noFontFallback=a.noFontFallback?a.noFontFallback:!1;for(var c=0;c<d.length;c++){var f=d[c];if(f.attributes.rel&&f.attributes.href&&"stylesheet"==f.attributes.rel.value){var g=f.attributes.href.value,m=u("a");m.href=g;var v=m.protocol+"//"+m.host+m.pathname+m.search;o.stylesheets.push(v)}}for(c=0;c<s.length;c++){var x=t.getComputedStyle(s[c],null).getPropertyValue("background-image"),b=s[c].getAttribute("data-background-src"),S=null;S=null==b?x:b;var C=null,E="?"+a.domain+"/";if(0===S.indexOf(E))C=S.slice(1);else if(-1!=S.indexOf(E)){var k=S.substr(S.indexOf(E)).slice(1),T=k.match(/([^\"]*)"?\)/);null!=T&&(C=T[1])}if(null!=C){var L=n(C,a);L&&i("background",s[c],L,o)}}for(c=0;c<h.length;c++){var O=h[c],F={};try{F.data=O.getAttribute("data"),F.dataSrc=O.getAttribute("data-src")}catch(z){}var M=null!=F.data&&0===F.data.indexOf(a.domain),D=null!=F.dataSrc&&0===F.dataSrc.indexOf(a.domain);M?r(a,o,F.data,O):D&&r(a,o,F.dataSrc,O)}for(c=0;c<l.length;c++){var R=l[c],j={};try{j.src=R.getAttribute("src"),j.dataSrc=R.getAttribute("data-src"),j.rendered=R.getAttribute("data-holder-rendered")}catch(z){}var B=null!=j.src,P=null!=j.dataSrc&&0===j.dataSrc.indexOf(a.domain),N=null!=j.rendered&&"true"==j.rendered;B?0===j.src.indexOf(a.domain)?r(a,o,j.src,R):P&&(N?r(a,o,j.dataSrc,R):w({src:j.src,options:a,renderSettings:o,dataSrc:j.dataSrc,image:R},function(e,t){e||r(t.options,t.renderSettings,t.dataSrc,t.image)})):P&&r(a,o,j.dataSrc,R)}return this},invisibleErrorFn:function(){return function(e){if(e.hasAttribute("data-holder-invisible"))throw"Holder: invisible placeholder"}}};k.add_theme=k.addTheme,k.add_image=k.addImage,k.invisible_error_fn=k.invisibleErrorFn;var A={settings:{domain:"holder.js",images:"img",objects:"object",bgnodes:"body .holderjs",stylenodes:"head link.holderjs",stylesheets:[],themes:{gray:{background:"#EEEEEE",foreground:"#AAAAAA"},social:{background:"#3a5a97",foreground:"#FFFFFF"},industrial:{background:"#434A52",foreground:"#C2F200"},sky:{background:"#0D8FDB",foreground:"#FFFFFF"},vine:{background:"#39DBAC",foreground:"#1E292C"},lava:{background:"#F8591A",foreground:"#1C2846",size:12}}},flags:{dimensions:{regex:/^(\d+)x(\d+)$/,output:function(e){var t=this.regex.exec(e);return{width:+t[1],height:+t[2]}}},fluid:{regex:/^([0-9]+%?)x([0-9]+%?)$/,output:function(e){var t=this.regex.exec(e);return{width:t[1],height:t[2]}}},colors:{regex:/(?:#|\^)([0-9a-f]{3,})\:(?:#|\^)([0-9a-f]{3,})/i,output:function(e){var t=this.regex.exec(e);return{foreground:"#"+t[2],background:"#"+t[1]}}},text:{regex:/text\:(.*)/,output:function(e){return this.regex.exec(e)[1].replace("\\/","/")}},font:{regex:/font\:(.*)/,output:function(e){return this.regex.exec(e)[1]}},auto:{regex:/^auto$/},textmode:{regex:/textmode\:(.*)/,output:function(e){return this.regex.exec(e)[1]}},random:{regex:/^random$/}}},T=function(){var e=null,t=null,r=null;return function(n){var i=n.root;if(A.setup.supportsSVG){var o=!1,a=function(e){return E.createTextNode(e)};null==e&&(o=!0),e=f(e,i.properties.width,i.properties.height),o&&(t=u("text",C),r=a(null),c(t,{x:0}),t.appendChild(r),e.appendChild(t),E.body.appendChild(e),e.style.visibility="hidden",e.style.position="absolute",e.style.top="-100%",e.style.left="-100%");var l=i.children.holderTextGroup,s=l.properties;c(t,{y:s.font.size,style:m({"font-weight":s.font.weight,"font-size":s.font.size+"px","font-family":s.font.family,"dominant-baseline":"middle"})}),r.nodeValue=s.text;var d=t.getBBox(),h=Math.ceil(d.width/(i.properties.width*A.setup.lineWrapRatio)),g=s.text.split(" "),p=s.text.match(/\\n/g);h+=null==p?0:p.length,r.nodeValue=s.text.replace(/[ ]+/g,"");var v=t.getComputedTextLength(),x=d.width-v,y=Math.round(x/Math.max(1,g.length-1)),w=[];if(h>1){r.nodeValue="";for(var b=0;b<g.length;b++)if(0!==g[b].length){r.nodeValue=S(g[b]);var k=t.getBBox();w.push({text:g[b],width:k.width})}}return{spaceWidth:y,lineCount:h,boundingBox:d,words:w}}return!1}}(),L=function(){var e=u("canvas"),t=null;return function(r){null==t&&(t=e.getContext("2d"));var n=r.root;e.width=A.dpr(n.properties.width),e.height=A.dpr(n.properties.height),t.textBaseline="middle",t.fillStyle=n.children.holderBg.properties.fill,t.fillRect(0,0,A.dpr(n.children.holderBg.width),A.dpr(n.children.holderBg.height));{var i=n.children.holderTextGroup;i.properties}t.font=i.properties.font.weight+" "+A.dpr(i.properties.font.size)+"px "+i.properties.font.family+", monospace",t.fillStyle=i.properties.fill;for(var o in i.children){var a=i.children[o];for(var l in a.children){var s=a.children[l],d=A.dpr(i.x+a.x+s.x),h=A.dpr(i.y+a.y+s.y+i.properties.leading/2);t.fillText(s.properties.text,d,h)}}return e.toDataURL("image/png")}}(),O=function(){if(t.XMLSerializer){var e=f(null,0,0),r=u("rect",C);return e.appendChild(r),function(t,n){var i=t.root;f(e,i.properties.width,i.properties.height);for(var o=e.querySelectorAll("g"),a=0;a<o.length;a++)o[a].parentNode.removeChild(o[a]);c(r,{width:i.children.holderBg.width,height:i.children.holderBg.height,fill:i.children.holderBg.properties.fill});var l=i.children.holderTextGroup,s=l.properties,d=u("g",C);e.appendChild(d);for(var h in l.children){var p=l.children[h];for(var v in p.children){var x=p.children[v],y=l.x+p.x+x.x,w=l.y+p.y+x.y+l.properties.leading/2,b=u("text",C),S=E.createTextNode(null);c(b,{x:y,y:w,style:m({fill:s.fill,"font-weight":s.font.weight,"font-family":s.font.family+", monospace","font-size":s.font.size+"px","dominant-baseline":"central"})}),S.nodeValue=x.properties.text,b.appendChild(S),d.appendChild(b)}}var k="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(g(e,n))));return k}}}(),F=function(e){function t(e,t){for(var r in t)e[r]=t[r];return e}var r=1,n=augment.defclass({constructor:function(e){r++,this.parent=null,this.children={},this.id=r,this.name="n"+r,null!=e&&(this.name=e),this.x=0,this.y=0,this.z=0,this.width=0,this.height=0},resize:function(e,t){null!=e&&(this.width=e),null!=t&&(this.height=t)},moveTo:function(e,t,r){this.x=null!=e?e:this.x,this.y=null!=t?t:this.y,this.z=null!=r?r:this.z},add:function(e){var t=e.name;if(null!=this.children[t])throw"SceneGraph: child with that name already exists: "+t;this.children[t]=e,e.parent=this}}),i=augment(n,function(t){this.constructor=function(){t.constructor.call(this,"root"),this.properties=e}}),o=augment(n,function(e){function r(r,n){if(e.constructor.call(this,r),this.properties={fill:"#000"},null!=n)t(this.properties,n);else if(null!=r&&"string"!=typeof r)throw"SceneGraph: invalid node name"}this.Group=augment.extend(this,{constructor:r,type:"group"}),this.Rect=augment.extend(this,{constructor:r,type:"rect"}),this.Text=augment.extend(this,{constructor:function(e){r.call(this),this.properties.text=e},type:"text"})}),a=new i;return this.Shape=o,this.root=a,this};for(var z in A.flags)A.flags.hasOwnProperty(z)&&(A.flags[z].match=function(e){return e.match(this.regex)});A.setup={renderer:"html",debounce:100,ratio:1,supportsCanvas:!1,supportsSVG:!1,lineWrapRatio:.9,renderers:["html","canvas","svg"]},A.dpr=function(e){return e*A.setup.ratio},A.vars={preempted:!1,resizableImages:[],debounceTimer:null,cache:{}},function(){var e=1,r=1,n=u("canvas"),i=null;n.getContext&&-1!=n.toDataURL("image/png").indexOf("data:image/png")&&(A.setup.renderer="canvas",i=n.getContext("2d"),A.setup.supportsCanvas=!0),A.setup.supportsCanvas&&(e=t.devicePixelRatio||1,r=i.webkitBackingStorePixelRatio||i.mozBackingStorePixelRatio||i.msBackingStorePixelRatio||i.oBackingStorePixelRatio||i.backingStorePixelRatio||1),A.setup.ratio=e/r,E.createElementNS&&E.createElementNS(C,"svg").createSVGRect&&(A.setup.renderer="svg",A.setup.supportsSVG=!0)}(),e(k,"Holder",t),t.onDomReady&&t.onDomReady(function(){A.vars.preempted||k.run(),t.addEventListener?(t.addEventListener("resize",x,!1),t.addEventListener("orientationchange",x,!1)):t.attachEvent("onresize",x),"object"==typeof t.Turbolinks&&t.document.addEventListener("page:change",function(){k.run()})})}(function(e,t,r){var n="function"==typeof define&&define.amd;n?define(e):r[t]=e},this);
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{//window.mobilecheck = function() {
//    var check = false;
//    (function(a){(jQuery.browser=jQuery.browser||{}).mobile=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);
//    return check;
//    console.log(check);
//    Don't like this method as much because of some of the overhead. Afraid it's not scalable going forward. Trying method below.
//}
var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    } };
// to use: if( isMobile.any() ) do something ;
// if(! isMobile.any() ) do something;


}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{
/*!
 * iCheck v2.0.0, http://git.io/arlzeA
 * ===================================
 * Cross-platform checkboxes and radio buttons customization
 *
 * (c) Damir Sultanov - http://fronteed.com
 * MIT Licensed
 */

(function(win, doc, $) {

  // prevent multiple includes
  if (!win.ichecked) {
    win.ichecked = function() {
      $ = win.jQuery || win.Zepto;

      // default options
      var defaults = {

        // auto init on domready
        autoInit: true,

        // auto handle ajax loaded inputs
        autoAjax: true,

        // remove 300ms click delay on touch devices
        tap: true,

        // customization class names
        checkboxClass: 'icheckbox',
        radioClass: 'iradio',

        checkedClass: 'checked',
        disabledClass: 'disabled',
        indeterminateClass: 'indeterminate',

        hoverClass: 'hover',
        // focusClass: 'focus',
        // activeClass: 'active',

        // default callbacks
        callbacks: {
          ifCreated: false
        },

        // appended class names
        classes: {
          base: 'icheck',
          div: '#-item', // {base}-item
          area: '#-area-', // {base}-area-{value}
          input: '#-input', // {base}-input
          label: '#-label' // {base}-label
        }
      };

      // extend default options
      win.icheck = $.extend(defaults, win.icheck);

      // useragent sniffing
      var ua = win.navigator.userAgent;
      var ie = /MSIE [5-8]/.test(ua) || doc.documentMode < 9;
      var operaMini = /Opera Mini/.test(ua);

      // classes cache
      var baseClass = defaults.classes.base;
      var divClass = defaults.classes.div.replace('#', baseClass);
      var areaClass = defaults.classes.area.replace('#', baseClass);
      var nodeClass = defaults.classes.input.replace('#', baseClass);
      var labelClass = defaults.classes.label.replace('#', baseClass);

      // unset init classes
      delete defaults.classes;

      // default filter
      var filter = 'input[type=checkbox],input[type=radio]';

      // clickable areas container
      var areas = {};

      // hashes container
      var hashes = {};

      // hash recognizer
      var recognizer = new RegExp(baseClass + '\\[(.*?)\\]');

      // hash extractor
      var extract = function(className, matches, value) {
        if (!!className) {
          matches = recognizer.exec(className);

          if (matches && hashes[matches[1]]) {
            value = matches[1];
          }
        }

        return value;
      };

      // detect computed style support
      var computed = win.getComputedStyle;

      // detect pointer events support
      var isPointer = win.PointerEvent || win.MSPointerEvent;

      // detect touch events support
      var isTouch = 'ontouchend' in win;

      // detect mobile users
      var isMobile = /mobile|tablet|phone|ip(ad|od)|android|silk|webos/i.test(ua);

      // setup events
      var mouse = ['mouse', 'down', 'up', 'over', 'out']; // bubbling hover
      var pointer = win.PointerEvent ? ['pointer', mouse[1], mouse[2], mouse[3], mouse[4]] : ['MSPointer', 'Down', 'Up', 'Over', 'Out'];
      var touch = ['touch', 'start', 'end'];
      var noMouse = (isTouch && isMobile) || isPointer;

      // choose events
      var hoverStart = noMouse ? (isTouch ? touch[0] + touch[1] : pointer[0] + pointer[3]) : mouse[0] + mouse[3];
      var hoverEnd = noMouse ? (isTouch ? touch[0] + touch[2] : pointer[0] + pointer[4]) : mouse[0] + mouse[4];
      var tapStart = noMouse ? (isTouch ? false : pointer[0] + pointer[1]) : mouse[0] + mouse[1];
      var tapEnd = noMouse ? (isTouch ? false : pointer[0] + pointer[2]) : mouse[0] + mouse[2];
      var hover = !operaMini ? hoverStart + '.i ' + hoverEnd + '.i ' : '';
      var tap = !operaMini && tapStart ? tapStart + '.i ' + tapEnd + '.i' : '';

      // styles options
      var styleTag;
      var styleList;
      var styleArea = defaults.areaStyle !== false ? 'position:absolute;display:block;content:"";top:#;bottom:#;left:#;right:#;' : 0;
      var styleInput = 'position:absolute!;display:block!;outline:none!;' + (defaults.debug ? '' : 'opacity:0!;z-index:-99!;clip:rect(0 0 0 0)!;');

      // styles addition
      var style = function(rules, selector, area) {
        if (!styleTag) {

          // create container
          styleTag = doc.createElement('style');

          // append to header
          (doc.head || doc.getElementsByTagName('head')[0]).appendChild(styleTag);

          // webkit hack
          if (!win.createPopup) {
            styleTag.appendChild(doc.createTextNode(''));
          }

          styleList = styleTag.sheet || styleTag.styleSheet;
        }

        // choose selector
        if (!selector) {
          selector = 'div.' + (area ? areaClass + area + ':after' : divClass + ' input.' + nodeClass);
        }

        // replace shorthand rules
        rules = rules.replace(/!/g, ' !important');

        // append styles
        if (styleList.addRule) {
          styleList.addRule(selector, rules, 0);
        } else {
          styleList.insertRule(selector + '{' + rules + '}', 0);
        }
      };

      // append input's styles
      style(styleInput);

      // append styler's styles
      if ((isTouch && isMobile) || operaMini) {

        // force custor:pointer for mobile devices
        style('cursor:pointer!;', 'label.' + labelClass + ',div.' + divClass);
      }

      // append iframe's styles
      style('display:none!', 'iframe.icheck-frame'); // used to handle ajax-loaded inputs

      // class toggler
      var toggle = function(node, className, status, currentClass, updatedClass, addClass, removeClass) {
        currentClass = node.className;

        if (!!currentClass) {
          updatedClass = ' ' + currentClass + ' ';

          // add class
          if (status === 1) {
            addClass = className;

          // remove class
          } else if (status === 0) {
            removeClass = className;

          // add and remove class
          } else {
            addClass = className[0];
            removeClass = className[1];
          }

          // add class
          if (!!addClass && updatedClass.indexOf(' ' + addClass + ' ') < 0) {
            updatedClass += addClass + ' ';
          }

          // remove class
          if (!!removeClass && ~updatedClass.indexOf(' ' + removeClass + ' ')) {
            updatedClass = updatedClass.replace(' ' + removeClass + ' ', ' ');
          }

          // trim class
          updatedClass = updatedClass.replace(/^\s+|\s+$/g, '');

          // update class
          if (updatedClass !== currentClass) {
            node.className = updatedClass;
          }

          // return updated class
          return updatedClass;
        }
      };

      // traces remover
      var tidy = function(node, key, trigger, settings, className, parent) {
        if (hashes[key]) {
          settings = hashes[key];
          className = settings.className;
          parent = $(closest(node, 'div', className));

          // prevent overlapping
          if (parent.length) {

            // input
            $(node).removeClass(nodeClass + ' ' + className).attr('style', settings.style);

            // label
            $('label.' + settings.esc).removeClass(labelClass + ' ' + className);

            // parent
            $(parent).replaceWith($(node));

            // callback
            if (trigger) {
              callback(node, key, trigger);
            }
          }

          // unset current key
          hashes[key] = false;
        }
      };

      // nodes inspector
      var inspect = function(object, node, stack, direct, indirect) {
        stack = [];
        direct = object.length;

        // inspect object
        while (direct--) {
          node = object[direct];

          // direct input
          if (node.type) {

            // checkbox or radio button
            if (~filter.indexOf(node.type)) {
              stack.push(node);
            }

          // indirect input
          } else {
            node = $(node).find(filter);
            indirect = node.length;

            while (indirect--) {
              stack.push(node[indirect]);
            }
          }
        }

        return stack;
      };

      // parent searcher
      var closest = function(node, tag, className, parent) {
        while (node && node.nodeType !== 9) {
          node = node.parentNode;

          if (node && node.tagName == tag.toUpperCase() && ~node.className.indexOf(className)) {
            parent = node;
            break;
          }
        }

        return parent;
      };

      // callbacks farm
      var callback = function(node, key, name) {
        name = 'if' + name;

        // callbacks are allowed
        if (hashes[key].callbacks !== false) {

          // direct callback
          if (typeof hashes[key].callbacks[name] == 'function') {
            hashes[key].callbacks[name](node, hashes[key]);
          }

          // indirect callback
          if (hashes[key].callbacks[name] !== false) {
            $(node).trigger(name);
          }
        }
      };

      // selection processor
      var process = function(data, options, ajax, silent) {

        // get inputs
        var elements = inspect(data);
        var element = elements.length;

        // loop through inputs
        while (element--) {
          var node = elements[element];
          var nodeAttr = node.attributes;
          var nodeAttrCache = {};
          var nodeAttrLength = nodeAttr.length;
          var nodeAttrName;
          var nodeAttrValue;
          var nodeData = {};
          var nodeDataCache = {}; // merged data
          var nodeDataProperty;
          var nodeId = node.id;
          var nodeInherit;
          var nodeInheritItem;
          var nodeInheritLength;
          var nodeString = node.className;
          var nodeStyle;
          var nodeType = node.type;
          var queryData = $.cache ? $.cache[node[$.expando]] : 0; // cached data
          var settings;
          var key = extract(nodeString);
          var keyClass;
          var handle;
          var styler;
          var stylerClass = '';
          var stylerStyle;
          var area = false;
          var label;
          var labelDirect;
          var labelIndirect;
          var labelKey;
          var labelString;
          var labels = [];
          var labelsLength;
          var fastClass = win.FastClick ? ' needsclick' : '';

          // parse options from HTML attributes
          while (nodeAttrLength--) {
            nodeAttrName = nodeAttr[nodeAttrLength].name;
            nodeAttrValue = nodeAttr[nodeAttrLength].value;

            if (~nodeAttrName.indexOf('data-')) {
              nodeData[nodeAttrName.substr(5)] = nodeAttrValue;
            }

            if (nodeAttrName == 'style') {
              nodeStyle = nodeAttrValue;
            }

            nodeAttrCache[nodeAttrName] = nodeAttrValue;
          }

          // parse options from jQuery or Zepto cache
          if (queryData && queryData.data) {
            nodeData = $.extend(nodeData, queryData.data);
          }

          // parse merged options
          for (nodeDataProperty in nodeData) {
            nodeAttrValue = nodeData[nodeDataProperty];

            if (nodeAttrValue == 'true' || nodeAttrValue == 'false') {
              nodeAttrValue = nodeAttrValue == 'true';
            }

            nodeDataCache[nodeDataProperty.replace(/checkbox|radio|class|id|label/g, function(string, position) {
              return position === 0 ? string : string.charAt(0).toUpperCase() + string.slice(1);
            })] = nodeAttrValue;
          }

          // merge options
          settings = $.extend({}, defaults, win.icheck, nodeDataCache, options);

          // input type filter
          handle = settings.handle;

          if (handle !== 'checkbox' && handle !== 'radio') {
            handle = filter;
          }

          // prevent unwanted init
          if (settings.init !== false && ~handle.indexOf(nodeType)) {

            // tidy before processing
            if (key) {
              tidy(node, key);
            }

            // generate random key
            while(!hashes[key]) {
              key = Math.random().toString(36).substr(2, 5); // 5 symbols

              if (!hashes[key]) {
                keyClass = baseClass + '[' + key + ']';
                break;
              }
            }

            // prevent unwanted duplicates
            delete settings.autoInit;
            delete settings.autoAjax;

            // save settings
            settings.style = nodeStyle || '';
            settings.className = keyClass;
            settings.esc = keyClass.replace(/(\[|\])/g, '\\$1');
            hashes[key] = settings;

            // find direct label
            labelDirect = closest(node, 'label', '');

            if (labelDirect) {

              // normalize "for" attribute
              if (!!!labelDirect.htmlFor && !!nodeId) {
                labelDirect.htmlFor = nodeId;
              }

              labels.push(labelDirect);
            }

            // find indirect label
            if (!!nodeId) {
              labelIndirect = $('label[for="' + nodeId + '"]');

              // merge labels
              while (labelIndirect.length--) {
                label = labelIndirect[labelIndirect.length];

                if (label !== labelDirect) {
                  labels.push(label);
                }
              }
            }

            // loop through labels
            labelsLength = labels.length;

            while (labelsLength--) {
              label = labels[labelsLength];
              labelString = label.className;
              labelKey = extract(labelString);

              // remove previous key
              if (labelKey) {
                labelString = toggle(label, baseClass + '[' + labelKey + ']', 0);
              } else {
                labelString = (!!labelString ? labelString + ' ' : '') + labelClass;
              }

              // update label's class
              label.className = labelString + ' ' + keyClass + fastClass;
            }

            // prepare styler
            styler = doc.createElement('div');

            // parse inherited options
            if (!!settings.inherit) {
              nodeInherit = settings.inherit.split(/\s*,\s*/);
              nodeInheritLength = nodeInherit.length;

              while (nodeInheritLength--) {
                nodeInheritItem = nodeInherit[nodeInheritLength];

                if (nodeAttrCache[nodeInheritItem] !== undefined) {
                  if (nodeInheritItem == 'class') {
                    stylerClass += nodeAttrCache[nodeInheritItem] + ' ';
                  } else {
                    styler.setAttribute(nodeInheritItem, nodeInheritItem == 'id' ? baseClass + '-' + nodeAttrCache[nodeInheritItem] : nodeAttrCache[nodeInheritItem]);
                  }
                }
              }
            }

            // set input's type class
            stylerClass += settings[nodeType + 'Class'];

            // set styler's key
            stylerClass += ' ' + divClass + ' ' + keyClass;

            // append area styles
            if (settings.area && styleArea) {
              area = ('' + settings.area).replace(/%|px|em|\+|-/g, '') | 0;

              if (area) {

                // append area's styles
                if (!areas[area]) {
                  style(styleArea.replace(/#/g, '-' + area + '%'), false, area);
                  areas[area] = true;
                }

                stylerClass += ' ' + areaClass + area;
              }
            }

            // update styler's class
            styler.className = stylerClass + fastClass;

            // update node's class
            node.className = (!!nodeString ? nodeString + ' ' : '') + nodeClass + ' ' + keyClass;

            // replace node
            node.parentNode.replaceChild(styler, node);

            // append node
            styler.appendChild(node);

            // append additions
            if (!!settings.insert) {
              $(styler).append(settings.insert);
            }

            // set relative position
            if (area) {

              // get styler's position
              if (computed) {
                stylerStyle = computed(styler, null).getPropertyValue('position');
              } else {
                stylerStyle = styler.currentStyle.position;
              }

              // update styler's position
              if (stylerStyle == 'static') {
                styler.style.position = 'relative';
              }
            }

            // operate
            operate(node, styler, key, 'updated', true, false, ajax);
            hashes[key].done = true;

            // ifCreated callback
            if (!silent) {
              callback(node, key, 'Created');
            }
          }
        }
      };

      // operations center
      var operate = function(node, parent, key, method, silent, before, ajax) {
        var settings = hashes[key];
        var states = {};
        var changes = {};

        // current states
        states.checked = [node.checked, 'Checked', 'Unchecked'];

        if ((!before || ajax) && method !== 'click') {
          states.disabled = [node.disabled, 'Disabled', 'Enabled'];
          states.indeterminate = [node.getAttribute('indeterminate') == 'true' || !!node.indeterminate, 'Indeterminate', 'Determinate'];
        }

        // methods
        if (method == 'updated' || method == 'click') {
          changes.checked = before ? !states.checked[0] : states.checked[0];

          if ((!before || ajax) && method !== 'click') {
            changes.disabled = states.disabled[0];
            changes.indeterminate = states.indeterminate[0];
          }

        } else if (method == 'checked' || method == 'unchecked') {
          changes.checked = method == 'checked';

        } else if (method == 'disabled' || method == 'enabled') {
          changes.disabled = method == 'disabled';

        } else if (method == 'indeterminate' || method == 'determinate') {
          changes.indeterminate = method !== 'determinate';

        // "toggle" method
        } else {
          changes.checked = !states.checked[0];
        }

        // apply changes
        change(node, parent, states, changes, key, settings, method, silent, before, ajax);
      };

      // state changer
      var change = function(node, parent, states, changes, key, settings, method, silent, before, ajax, loop) {
        var type = node.type;
        var typeCapital = type == 'radio' ? 'Radio' : 'Checkbox';
        var property;
        var value;
        var classes;
        var inputClass;
        var label;
        var labelClass = 'LabelClass';
        var form;
        var radios;
        var radiosLength;
        var radio;
        var radioKey;
        var radioStates;
        var radioChanges;
        var changed;
        var toggled;

        // check parent
        if (!parent) {
          parent = closest(node, 'div', settings.className);
        }

        // continue if parent exists
        if (parent) {

          // detect changes
          for (property in changes) {
            value = changes[property];

            // update node's property
            if (states[property][0] !== value && method !== 'updated' && method !== 'click') {
              node[property] = value;
            }

            // update ajax attributes
            if (ajax) {
              if (value) {
                node.setAttribute(property, property);
              } else {
                node.removeAttribute(property);
              }
            }

            // update key's property
            if (settings[property] !== value) {
              settings[property] = value;
              changed = true;

              if (property == 'checked') {
                toggled = true;

                // find assigned radios
                if (!loop && value && (!!hashes[key].done || ajax) && type == 'radio' && !!node.name) {
                  form = closest(node, 'form', '');
                  radios = 'input[name="' + node.name + '"]';
                  radios = form && !ajax ? $(form).find(radios) : $(radios);
                  radiosLength = radios.length;

                  while (radiosLength--) {
                    radio = radios[radiosLength];
                    radioKey = extract(radio.className);

                    // toggle radios
                    if (node !== radio && hashes[radioKey] && hashes[radioKey].checked) {
                      radioStates = {checked: [true, 'Checked', 'Unchecked']};
                      radioChanges = {checked: false};

                      change(radio, false, radioStates, radioChanges, radioKey, hashes[radioKey], 'updated', silent, before, ajax, true);
                    }
                  }
                }
              }

              // cache classes
              classes = [
                settings[property + 'Class'], // 0, example: checkedClass
                settings[property + typeCapital + 'Class'], // 1, example: checkedCheckboxClass
                settings[states[property][1] + 'Class'], // 2, example: uncheckedClass
                settings[states[property][1] + typeCapital + 'Class'], // 3, example: uncheckedCheckboxClass
                settings[property + labelClass] // 4, example: checkedLabelClass
              ];

              // value == false
              inputClass = [classes[3] || classes[2], classes[1] || classes[0]];

              // value == true
              if (value) {
                inputClass.reverse();
              }

              // update parent's class
              toggle(parent, inputClass);

              // update labels's class
              if (!!settings.mirror && !!classes[4]) {
                label = $('label.' + settings.esc);

                while (label.length--) {
                  toggle(label[label.length], classes[4], value ? 1 : 0);
                }
              }

              // callback
              if (!silent || loop) {
                callback(node, key, states[property][value ? 1 : 2]); // ifChecked or ifUnchecked
              }
            }
          }

          // additional callbacks
          if (!silent || loop) {
            if (changed) {
              callback(node, key, 'Changed'); // ifChanged
            }

            if (toggled) {
              callback(node, key, 'Toggled'); // ifToggled
            }
          }

          // cursor addition
          if (!!settings.cursor && !isMobile) {

            // 'pointer' for enabled
            if (!settings.disabled && !settings.pointer) {
              parent.style.cursor = 'pointer';
              settings.pointer = true;

            // 'default' for disabled
            } else if (settings.disabled && settings.pointer) {
              parent.style.cursor = 'default';
              settings.pointer = false;
            }
          }

          // update settings
          hashes[key] = settings;
        }
      };

      // plugin definition
      $.fn.icheck = function(options, fire) {

        // detect methods
        if (/^(checked|unchecked|indeterminate|determinate|disabled|enabled|updated|toggle|destroy|data|styler)$/.test(options)) {
          var items = inspect(this);
          var itemsLength = items.length;

          // loop through inputs
          while (itemsLength--) {
            var item = items[itemsLength];
            var key = extract(item.className);

            if (key) {

              // 'data' method
              if (options == 'data') {
                return hashes[key];

              // 'styler' method
              } else if (options == 'styler') {
                return closest(item, 'div', hashes[key].className);

              } else {
                if (options == 'destroy') {
                  tidy(item, key, 'Destroyed');
                } else {
                  operate(item, false, key, options);
                }

                // callback
                if (typeof fire == 'function') {
                  fire(item);
                }
              }
            }
          }

        // basic setup
        } else if (typeof options == 'object' || !options) {
          process(this, options || {});
        }

        // chain
        return this;
      };

      // cached last key
      var lastKey;

      // bind label and styler
      $(doc).on('click.i ' + hover + tap, 'label.' + labelClass + ',div.' + divClass, function(event) {
        var self = this;
        var key = extract(self.className);

        if (key) {
          var emitter = event.type;
          var settings = hashes[key];
          var className = settings.esc; // escaped class name
          var div = self.tagName == 'DIV';
          var input;
          var target;
          var partner;
          var activate;
          var states = [
            ['label', settings.activeLabelClass, settings.hoverLabelClass],
            ['div', settings.activeClass, settings.hoverClass]
          ];

          // reverse array
          if (div) {
            states.reverse();
          }
          
          // active state
          if (emitter == tapStart || emitter == tapEnd) {

            // toggle self's active class
            if (!!states[0][1]) {
              toggle(self, states[0][1], emitter == tapStart ? 1 : 0);
            }

            // toggle partner's active class
            if (!!settings.mirror && !!states[1][1]) {
              partner = $(states[1][0] + '.' + className);

              while (partner.length--) {
                toggle(partner[partner.length], states[1][1], emitter == tapStart ? 1 : 0);
              }
            }

            // fast click
            if (div && emitter == tapEnd && !!settings.tap && isMobile && isPointer && !operaMini) {
              activate = true;
            }

          // hover state
          } else if (emitter == hoverStart || emitter == hoverEnd) {

            // toggle self's hover class
            if (!!states[0][2]) {
              toggle(self, states[0][2], emitter == hoverStart ? 1 : 0);
            }

            // toggle partner's hover class
            if (!!settings.mirror && !!states[1][2]) {
              partner = $(states[1][0] + '.' + className);

              while (partner.length--) {
                toggle(partner[partner.length], states[1][2], emitter == hoverStart ? 1 : 0);
              }
            }

            // fast click
            if (div && emitter == hoverEnd && !!settings.tap && isMobile && isTouch && !operaMini) {
              activate = true;
            }

          // click
          } else if (div) {
            if (!(isMobile && (isTouch || isPointer)) || !!!settings.tap || operaMini) {
              activate = true;
            }
          }

          // trigger input's click
          if (activate) {

            // currentTarget hack
            setTimeout(function() {
              target = event.currentTarget || {};

              if (target.tagName !== 'LABEL') {
                if (!settings.change || (+new Date() - settings.change > 100)) {
                  input = $(self).find('input.' + className).click();

                  if (ie || operaMini) {
                    input.change();
                  }
                }
              }
            }, 2);
          }
        }

      // bind input
      }).on('click.i change.i focusin.i focusout.i keyup.i keydown.i', 'input.' + nodeClass, function(event) {
        var self = this;
        var key = extract(self.className);
        if (key) {
          var emitter = event.type;
          var settings = hashes[key];
          var className = settings.esc; // escaped class name
          var parent = emitter == 'click' ? false : closest(self, 'div', settings.className);
          var label;
          var states;

          // click
          if (emitter == 'click') {
            hashes[key].change = +new Date();

            // prevent event bubbling to parent
            event.stopPropagation();

          // change
          } else if (emitter == 'change') {

            if (parent && !self.disabled) {
              operate(self, parent, key, 'click'); // 'click' method
            }

          // focus state
          } else if (~emitter.indexOf('focus')) {
            states = [settings.focusClass, settings.focusLabelClass];

            // toggle parent's focus class
            if (!!states[0] && parent) {
              toggle(parent, states[0], emitter == 'focusin' ? 1 : 0);
            }

            // toggle label's focus class
            if (!!settings.mirror && !!states[1]) {
              label = $('label.' + className);

              while (label.length--) {
                toggle(label[label.length], states[1], emitter == 'focusin' ? 1 : 0);
              }
            }

          // keyup or keydown (event fired before state is changed, except Opera 9-12)
          } else if (parent && !self.disabled) {

            // keyup
            if (emitter == 'keyup') {

              // spacebar or arrow
              if (self.type == 'checkbox' && event.keyCode == 32 && settings.keydown || self.type == 'radio' && !self.checked) {
                operate(self, parent, key, 'click', false, true); // 'toggle' method
              }
              lastKey = key;
              hashes[key].keydown = hashes[lastKey].keydown = false;

            // keydown
            } else {
              lastKey = key;
              hashes[key].keydown = true;
            }
          }
        }

      // domready
      }).ready(function() {

        // auto init
        if (win.icheck.autoInit) {
          $('.' + baseClass).icheck();
        }

        // auto ajax
        if (win.jQuery) {

          // body selector cache
          var body = doc.body || doc.getElementsByTagName('body')[0];

          // apply converter
          $.ajaxSetup({
            converters: {
              'text html': function(data) {
                if (win.icheck.autoAjax && body) {
                  var frame = doc.createElement('iframe'); // create container
                  var frameData;

                  // set attributes
                  if (!ie) {
                    frame.style = 'display:none';
                  }

                  frame.className = 'iframe.icheck-frame';
                  frame.src ='about:blank';

                  // append container to document
                  body.appendChild(frame);

                  // save container's content
                  frameData = frame.contentDocument ? frame.contentDocument : frame.contentWindow.document;

                  // append data to content
                  frameData.open();
                  frameData.write(data);
                  frameData.close();

                  // remove container from document
                  body.removeChild(frame);

                  // setup object
                  frameData = $(frameData);

                  // customize inputs
                  process(frameData.find('.' + baseClass), {}, true);

                  // extract HTML
                  frameData = frameData[0];
                  data = (frameData.body || frameData.getElementsByTagName('body')[0]).innerHTML;
                  frameData = null; // prevent memory leaks
                }

                return data;
              }
            }
          });
        }
      });
    };

    // expose iCheck as an AMD module
    if (typeof define == 'function' && define.amd) {
      define('icheck', [win.jQuery ? 'jquery' : 'zepto'], win.ichecked);
    } else {
      win.ichecked();
    }
  }
}(window, document));
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{$(document).ready(function() {
var modalPos;
// ---------------------------------------------- BOOSTRAP/VENDOR JS INIT

  // on desktop
  $('.search-bg .dropdown-menu li a').on('click', function(e) {
    e.preventDefault();
    $('.dropdown-toggle .search-category').text($(this).text());
    var dynamicDropdownHook = $(this).parents(".search-bg").find("#search-dropdown").innerWidth() + 15;
    if($("html").attr("dir")=="ltr"){
	    $(this).parents(".search-bg").find(".search-input").css("padding-left",dynamicDropdownHook).focus(); // Do not remove - VV
	    $(this).parents(".search-bg").find(".predictive-results").css("left", dynamicDropdownHook); // Do not remove - VV
        if($("body").hasClass("ie10")){ /* Coz- issue in IE10 - search text not realigning - VV*/
            var el=$(this).parents(".search-bg").find(".search-input");
            $(el).val($(el).val()+" ");
            $(el).val($(el).val().trim());
        }
	   }
    else{
    	$(this).parents(".search-bg").find(".search-input").css("padding-right",dynamicDropdownHook).focus(); // Do not remove - VV
	    $(this).parents(".search-bg").find(".predictive-results").css("right", dynamicDropdownHook); // Do not remove - VV
	    if($("body").hasClass("ie10")){ /* Coz- issue in IE10 - search text not realigning - VV*/
            var el=$(this).parents(".search-bg").find(".search-input");
            $(el).val($(el).val()+" ");
            $(el).val($(el).val().trim());
        }
    }
    
    $(this).parents(".search-bg").find(".typeaheadHook").val(dynamicDropdownHook); // Do not remove - VV
    $('.dropdown-toggle .search-category').val(($(this).attr("data-value")));
    $('.search-bg #searchCategory').val(($(this).parent("li").index()));
   
    $(this).parents(".dropdown").removeClass("open");
  });

  // if the results dropdown is open and the select dropdown is clicked, hide the results
  $('.search-bg .dropdown-toggle').on('click', function() {
    $('.predictive-results').hide();
  });

  $('.search-bg input').on('click', function() {
    $('.predictive-results').show();
  });

  // on iOS (Safari), remove the keyboard on active inputs when rotating device so layout can readjust
  if (window.addEventListener) {
    window.addEventListener('orientationchange', function() {
      $('.modal input, .modal textarea').blur();
    });
  }

// ---------------------------------------------- MOBILE TABS

  $('.hp-nav-tabs-bg a').on('tap click', function(e) {
    e.preventDefault();
    $('.tab-content').addClass('open');
  });

// ---------------------------------------------- PCP VIEW TOGGLE

  $('.view-button').on('tap click', function(e) {
    e.preventDefault();
    $('.view-button').removeClass('active');
    $(this).addClass('active');

    var viewType = $(this).attr('id');
    $('#product-grid .product a').removeAttr('style');
    $('#product-grid').removeClass();
    $('#product-grid').addClass(viewType);
  });
  
  $('#product-grid .product a').matchHeight();
  $('select.to-fancify').fancySelect(); 

  // -------------------------------------------- AFFIX SIDEBAR

  $(window).scroll(function() {    
    var scroll = $(window).scrollTop();
    if (scroll >= 300) {
      $('#styleguide-sidebar').addClass("affix");
    } else {
      $('#styleguide-sidebar').removeClass("affix");
    }
  });
// ---------------------------------------------- IOS FIXES FOR SEARCH HEADER

if (Modernizr.touch && (window.innerWidth <= 800 || document.documentElement.clientWidth <= 800)) {
  $(document)
    .on('focus', 'input', function(e) {
      $('body').addClass('fixfixed');
      $('.hp-desktop-header').removeClass('sticky');
    })
    .on('blur', 'input', function(e) {
    $('body').removeClass('fixfixed');
    $('.hp-desktop-header').addClass('sticky');
  });
}


// ---------------------------------------------- NAV .ACTIVE FOR BOOTSTRAP ONLY
   /* Do not uncomment - Himanshu
  var pathname = window.location.pathname;
  
  if(pathname.indexOf('index') > -1) {
    $('#nav-home').addClass('active');

  } else if (pathname.indexOf('products') > -1 || pathname.indexOf('pdp') > -1 || pathname.indexOf('pcp') > -1) {
    $('#nav-products').addClass('active');
    $('#page-title').text('- Products');

  } else if (pathname.indexOf('swd') > -1) {
    $('#nav-swd').addClass('active');
    $('#page-title').text('- Software & Drivers');

  } else if (pathname.indexOf('contact') > -1 || pathname.indexOf('mighty') > -1) {
    $('#nav-contact').addClass('active');
    $('#page-title').text('- Contact');

  } else if (pathname.indexOf('warranty') > -1) {
    $('#nav-products').addClass('active');

  } else {$('#nav-dev').addClass('active');}
*/
// ---------------------------------------------- ICHECK
  
  if($("#pageIdentifier").val() !== "SWDSelfServiceStep"){
      $('input').icheck({
        checkboxClass: 'icheckbox_flat-blue',
        radioClass: 'iradio_flat-blue',
        checkedClass: 'checked',
        disabledClass: 'disabled'
      });
  }


  $('.dispute-bar-container .close').on('tap click', function(){
    $(this).parents('.dispute-bar-container').slideUp();
  });

  // Making the search in tooltip rtl
  if($("html").attr("dir") == "rtl"){
    $(".with-tooltip").attr("data-placement","right");
  }
// ---------------------------------------------- MIGHTY-2 NUMBER SYNC

if ($('input[name="phone-number"]').length > 0) {
  $('input[name="phone"').on('change', function(){
    $('input[name="phone-number"]').val($(this).val());
  });
}

/*    if ($('input[type="tel"]').length > 0) {
        $('input[type="tel"]').on('change', function(){
            $('input[type="tel"]').val($(this).val());
        });
    }*/
// ---------------------------------------------- MAKE CONTACT TILES EQUAL HEIGHTS

  $('.tile-block').matchHeight();
  $('.equalize .column-block').matchHeight();
   $('.equalize .gray-block').matchHeight();

// -------------------------------------------- PROGRESS BAR
var incrementProgressBar = function(num){
  var $container = $('.progress-bar-container');
  var $bar = $('.progress-bar');
  var $status = $('.progress-bar-status');
  $bar.attr('aria-valuenow',num).css('width',num + '%');
  $status.text(num + '%');
};
window.runProgressBar = function(){
  incrementProgressBar(0);
  var progressStatus = 1;
  var progressInterval = setInterval(function(){
    incrementProgressBar(progressStatus);
    if (progressStatus === 100) {
      window.clearInterval(progressInterval);
      return;
    }
    progressStatus++;
  },20);
};
// --------------------------------------------MODAL
/*
$('[data-toggle="modal"]').click(function(e){
  modalPos = $(e.currentTarget).offset();
});

$('.modal').on('show.bs.modal',function(e){
modalPos = $(e.currentTarget).offset();
});

$('.modal').on('hidden.bs.modal',function(e){
  $('body').scrollTop(modalPos.top-200);
});
*/
/* do not uncomment
$(document).ready(function() {
  $('#refine-results-modal').modal('show');
}); */

 // ----------- Show all
 if ($('[data-toggle="show-all"]').length) {
  $('[data-toggle="show-all"]').click(function(){
    if ($(this).hasClass('all')){
      $('[data-toggle="show-all"]').html('Show all').removeClass('all');
      $('.pagination-count, .pagination-more, .pagination-less').show();
    }
    else {
      $('[data-toggle="show-all"]').html('Show less').addClass('all');
      $('.pagination-count, .pagination-more, .pagination-less').hide();
    }
  });
 }

 // --------------------------------------------- PSF
function isIE () {
  var userAgent = navigator.userAgent.toLowerCase();
  return (userAgent.indexOf('msie') != -1 || navigator.appVersion.indexOf('Trident/') > 0) ? true : false;
}
if ((!(window.ActiveXObject) && "ActiveXObject" in window) || isIE()) {
  /*$('.psf-link').addClass('psf-link-ie'); Commented by VV */
}

  // -------------------------------------------- Show/Hide Tabs not bootstrap modification

  if ($('[data-toggle="tab-box"]').length) {

      $('[data-toggle="tab-box"]').click(function(e){
        e.preventDefault();
        $(this).parent(".nav-tabs ~ li").removeClass('active');
        $(this).parent('li').addClass('active');
        var tabShow = $(this).attr('href');
       $(tabShow).addClass('active');

     });
  }

  // -------------------------------------------- Show/Hide secondary content like country-eligibility select model number modal moved - VV
  

  

  // --------------------------------------------- Ajax SWD Landing Page

  $('#ajaxMe').click(function (e) {
    e.preventDefault();
    $url = $(this).attr('href');
    $('#content').load($url, function(html) {
      if ( status == "error" ) {
        var msg = "Sorry but there was an error: ";
        $( "#content" ).html( msg + xhr.status + " " + xhr.statusText );
      }
    })
  });

  $('a.show-next').click( function(e) {
    e.preventDefault();
    var parentSection = $(this).closest("section").attr("id");
   $('#'+parentSection).hide();
    var next = $(this).attr('href');
    $(next).removeClass('hidden');
    $("html, body").animate();
    return false;
   });

  // -------------------------------------------- AFFIX steps bar but only on desktop and mobile after scrolling. Remove per HP-994. Jan 13, 2015
  //  $(window).scroll(function() {
  //    if (!$('#swd').hasClass('closure')) { //you don't want the sticky thing to happen on closure page because we're bringing in the nav again
  //      var scroll = $(window).scrollTop();
  //      if (scroll >= 75) {
  //        $('#steps-bar').addClass("sticky");
  //        $('.hp-hero').addClass("banner-margin");
  //
  //      } else {
  //        $('#steps-bar').removeClass("sticky");
  //        $('.hp-hero').removeClass("banner-margin");
  //      }
  //    }

/* --------------------------------------------- Style Upload Buttons with class .styledUpload
/* Do not merge - moved to portlet by HH
  if (!$('#uploadBtn').length) {
  } else {
    //var uploadFile = $('#uploadFile');
    $('#uploadBtn').on('change', function () {
      var fileName = $(this).val().replace("C:\\fakepath\\", "");
      $('#uploadFile').val(fileName);
      //$('#fileExit').removeClass('hidden');
      $('#uploadBtnText').prop('disabled', false);
      $('#uploadFile').prop('disabled', false);
    });
    //$('#fileExit').on('click', function () {
    //  $('#uploadFile').val('');
    //  $(this).addClass('hidden');
    //  return;
    //});

  } */
  // --------------------------------------------HOLDER
  
  // --------------------------------------------- Added after merge 5/7/2015 Style Upload Buttons with class .styledUpload
	  //upload handler moved to portlet do not merge- Himanshu
	     

    Holder.run({
        themes: {
            "concentraProduct": {
                background: "#0096d6",
                foreground: "#ffffff",
                size: 12
            }
        },
        images: "#placeholder"
    });

  // ------------------------------------------- Assign ID of url to body for styling HP-705

  var segment_str = window.location.pathname;
  var segment_array = segment_str.split( '/' );
  var last_segment = segment_array.pop();
  var id = last_segment.replace(/\.(htm[l]?|asp[x]?|php\#\w+|php|jsp)$/,'');
  var segment_class = id.split('-');
  $('body').attr('id', segment_class[2]);

// ------------------------------------------- Trigger Progress Bar Visually dont add it since we are not using it.

  // Change IMG SVG to inline SVG
  jQuery('img.svg').each(function(){
    var $img = jQuery(this);
    var imgID = $img.attr('id');
    var imgClass = $img.attr('class');
    var imgURL = $img.attr('src');

    jQuery.get(imgURL, function(data) {
      // Get the SVG tag, ignore the rest
      var $svg = jQuery(data).find('svg');

      // Add replaced image's ID to the new SVG
      if(typeof imgID !== 'undefined') {
        $svg = $svg.attr('id', imgID);
      }
      // Add replaced image's classes to the new SVG
      if(typeof imgClass !== 'undefined') {
        $svg = $svg.attr('class', imgClass+' replaced-svg');
      }

      // Remove any invalid XML tags as per http://validator.w3.org
      $svg = $svg.removeAttr('xmlns:a');

      // Replace image with new SVG
      $img.replaceWith($svg);

    }, 'xml');

  });
  // ------------------------------------------- Make Tabs Work differently if not in vertical alignment

 // ---------------------------------------------- INIT COMPONENTS
 if(window.location.href.indexOf('topic')<= -1){    /* fix for ALM 1532*/
   Tabs.init();
  }
  Dropdown.init();
  Accordion.init();
  //Checkboxes.init(); do not uncomment, 
  Pagination.init();
  //Filters.init();  Do not uncomment . initiatilzed in facets.js 
  ajaxSelect.init();
  narrowModal.init();
  Search.init();
  Tooltips.init();
  CLC.init();
  Header.init();
  //do not uncomment, not using their validateformValidate.init();
  PSF.init();
  SCF.init();
  
  OsSelector.init();
  Guided.init();
  //do not uncomment, not using this file selfGuided.init();
DownloadTable.init();
  // do not uncomment, not usingPdp.init();
});


}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{var searchcc = getCCLC("cc");
var searchlc = getCCLC("lc");


function paintFacets(productFacets,osFacets,topicFacets) {
	// check if there are no facets
	if((productFacets == undefined && osFacets == undefined && topicFacets == undefined) ||
		(JSON.stringify(productFacets)=="{}" && JSON.stringify(osFacets)=="{}" && topicFacets.length == 0)) {
		hideFacets();
		return;
	}

	// product facets display
	if(!$.isEmptyObject(productFacets)) {
		paintProductsFacets(productFacets);
	} else {
		$('#productFacets').hide();
	}

	// topic facets display
	if(topicFacets.length > 0) {
		paintTopicFacets(topicFacets);
	} else {
		$('#topicsFacets').hide();
	}

	// os facets display
	if(!$.isEmptyObject(osFacets)) {
		paintOSFacets(osFacets);
	} else {
		$('#osFacets').hide();
	}
	handleFacetsMobileView();
	osPrePopulation();
	Filters.init();
}

/* this function will bind click event for clear and clear all links in your selection section */
function bindClearFacets() {
	if ($('.applied-filters-item').length) {
		$('.filter-close.icon').on('click', facetsAjax);
		$('#filter-clear').on('click', facetsAjax);
	}
}

function handleFacetsMobileView() {
	$("#filter-close").on("click",function(){$("body").css("overflow","auto");});
	$("#filter-trigger").on("click",function(){$("body").css("overflow","hidden");});
}

/* create markup for products facets */
function paintProductsFacets(productFacets) {
	var hierarchyLevel1Ct = 0;
	for(var hierarchyLevel1 in productFacets) {
		var hierarchyLevel2 = productFacets[hierarchyLevel1];
		var level2Label, level2Id;

		// for upto 5 products
		if(hierarchyLevel1Ct<5) {
			$('div#productFacets ul.filter-level-1')
				.append('<li><label class="expandable"><span></span><a data-expandable="true" aria-expanded="false" href="javascript:void(0)">'+hierarchyLevel1+'</a></label><ul id="productFacets'+hierarchyLevel1Ct+'" class="filter-options filter-options-nested"></ul></li>');
		}
		else {
			// for more than 5 records
			$('div#productFacets ul.filter-level-1')
			.append('<li class="hideFacet"><label class="expandable"><span></span><a data-expandable="true" aria-expanded="false" href="javascript:void(0)">'+hierarchyLevel1+'</a></label><ul id="productFacets'+hierarchyLevel1Ct+'" class="filter-options filter-options-nested"></ul></li>');
		}

		for(var count2=0;count2<hierarchyLevel2.length;count2++) {
			level2Label = hierarchyLevel2[count2].split('|')[0];
			level2Id = hierarchyLevel2[count2].split('|')[1];
			$('ul#productFacets'+hierarchyLevel1Ct).append('<li><div class="checkbox"><label><input class="checkbox" type="checkbox" onclick="facetsAjax();">'+level2Label+
					'</input></label><input type="hidden" value="'+level2Id+'"></input></label></div></li>');

		}
		hierarchyLevel1Ct++;
	}

	// for more than 5 records, add show more products
	if(hierarchyLevel1Ct>5)
		$('div#productFacets ul.filter-level-1').append('<li><a href="javascript:void(0)" class="show-more in" data-more="more-category" data-text="'+$("#searchLessProducts").val()+'">'+$("#searchMoreProducts").val()+'</a></li>');

	$(".show-more").on("click",function() {
		if($(".show-more").hasClass('in')) {
			$('.hideFacet').css('display','block');
		} else {
			$('.hideFacet').css('display','none');
		}
	});
}
/*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('<li><label class="expandable"><span></span><a data-expandable="true" aria-expanded="false" href="javascript:void(0)">'+hierarchyLevel1+'</a></label><ul id="OSFacets'+hierarchyLevel1Ct+'" class="filter-options filter-options-nested"></ul></li>');
		}
		else {
			// for more than 5 records
			$('div#osFacets ul.filter-level-1')
			.append('<li class="hideFacetOS"><label class="expandable"><span></span><a data-expandable="true" aria-expanded="false" href="javascript:void(0)">'+hierarchyLevel1+'</a></label><ul id="OSFacets'+hierarchyLevel1Ct+'" class="filter-options filter-options-nested"></ul></li>');
		}
		for(var count2=0;count2<hierarchyLevel2.length;count2++) {
			level2Label = hierarchyLevel2[count2].split('|')[0];
			level2Id = hierarchyLevel2[count2].split('|')[1];
			$('ul#OSFacets'+hierarchyLevel1Ct).append('<li><div class="checkbox"><label><input class="checkbox" type="checkbox" onclick="facetsAjax();">'+level2Label+
					'</input></label><input type="hidden" value="'+level2Id+'"></input></label></div></li>');

		}
		hierarchyLevel1Ct++;
	}
	// for more than 5 records, add show more products
	if(hierarchyLevel1Ct>5)
		$('div#osFacets ul.filter-level-1').append('<li><a href="javascript:void(0)" class="show-more-OS in" data-more="more-category" data-text="'+$("#searchLessOS").val()+'">'+$("#searchMoreOS").val()+'</a></li>');

	$(".show-more-OS").on("click",function() {
		if($(".show-more-OS").hasClass('in')) {
			$('.hideFacetOS').css('display','block');
		} else {
			$('.hideFacetOS').css('display','none');
		}
	});
}

/*create markup for topic facets */
function paintTopicFacets(topicFacets) {
	var topicCount = topicFacets.length;
	var topicLabel,topicId,topicFacetMarkup = '';
	for(var count = 0; count < topicCount; count++) {
		topicLabel = topicFacets[count].split('|')[0];
		topicId = topicFacets[count].split('|')[1];
		topicFacetMarkup = topicFacetMarkup + '<li><div class="checkbox"><label><input class="checkbox" type="checkbox" onclick="facetsAjax();">'
			+topicLabel+'</label><input type="hidden" value="'+topicId+'"></div></li>';
	}
	$('#topicsFacets').find('.filter-options').append(topicFacetMarkup);
}

function facetsSearch() {
	var selectedFacetsId, finalSelectedFacet = "", facetVal;
	var productsFacets = "Products:";
	var osFacets = "OS:";
	var topicFacets = "Topics:";
	/*var allFacets = $('.icheckbox_flat-blue');

	$.each(allFacets,function(count,selectedFacet)  {
		if($(selectedFacet).hasClass('checked')){
			selectedFacetsId = $(selectedFacet).parent().siblings('input[type="hidden"]').val();
			facetVal = ($(selectedFacet).parents('ul.filter-options-nested').attr('id')) ? $(selectedFacet).parents('ul.filter-options-nested').attr('id') : 'topicFacets';
			if(selectedFacetsId!=undefined) {
				if(facetVal.indexOf('product')!=-1)
					productsFacets = productsFacets + selectedFacetsId + ',';
				else if(facetVal.indexOf('OS')!=-1)
					osFacets = osFacets + selectedFacetsId + ',';
				else
					topicFacets = topicFacets + selectedFacetsId + ',';
			}
		}
	})*/

	var allFacets = $('.icheck-input');

	$.each(allFacets,function(count,selectedFacet)  {
		if($(selectedFacet).is(':checked')){
			selectedFacetsId = $(selectedFacet).parents('label').siblings('input[type="hidden"]').val();
			facetVal = ($(selectedFacet).parents('ul.filter-options-nested').attr('id')) ? $(selectedFacet).parents('ul.filter-options-nested').attr('id') : 'topicFacets';
			if(selectedFacetsId!=undefined) {
				if(facetVal.indexOf('product')!=-1)
					productsFacets = productsFacets + selectedFacetsId + ',';
				else if(facetVal.indexOf('OS')!=-1)
					osFacets = osFacets + selectedFacetsId + ',';
				else
					topicFacets = topicFacets + selectedFacetsId + ',';
			}
		}
	})


	if(productsFacets.indexOf(",")!=-1) {
		productsFacets = productsFacets.substring(0,productsFacets.length-1);
		finalSelectedFacet = productsFacets + '|';
	}
	if(osFacets.indexOf(",")!=-1) {
		osFacets = osFacets.substring(0,osFacets.length-1);
		finalSelectedFacet = finalSelectedFacet + osFacets + '|';
	}

	if(topicFacets.indexOf(",")!=-1) {
		topicFacets = topicFacets.substring(0,topicFacets.length-1);
		finalSelectedFacet = finalSelectedFacet + topicFacets + '|';
	}

	if(finalSelectedFacet!="") {
		finalSelectedFacet = finalSelectedFacet.substring(0,finalSelectedFacet.length-1);
	}

	return finalSelectedFacet;
}




/*to create params for ajax call for pagination and facets search - Richa*/
function facetsPaginationParams(pageNum) {

	var searchQueryForDisplay = $("#oneboxtextsearch").val();
	var osValue = $("#interstitialSearchOSL1").val();
	var keywordValue = $("#interstitialSearchKeywords").val();
	var prodCatValue = $("#interstitialSearchProdCategoryL1").val();
	var contextClass = $("#contextClass").val();
	var contextValue = $("#contextValue").val();
	var pmNameValue = $("#pmNameValue").val();
	var pmNumberValue = $("#pmNumberValue").val();
	var pmSeriesValue = $("#pmSeriesValue").val();

	ajaxParam.paramData["cc"] = searchcc;
	if(noLocalResultsOnLoad){
		ajaxParam.paramData["lc"] = "en";
	}
	else{
		ajaxParam.paramData["lc"] = searchlc;
	}

	ajaxParam.paramData["searchContext"] = $("#searchCategory").val();
	ajaxParam.paramData["query"] = $('#searchQuery').val();
	ajaxParam.paramData["pageNum"] = pageNum;
	ajaxParam.paramData["os"] = osValue;
	ajaxParam.paramData["keyword"] = keywordValue;
	ajaxParam.paramData["prodCat"] = prodCatValue;
	ajaxParam.paramData["contextClass"] = contextClass;
	ajaxParam.paramData["contextValue"] = contextValue;
	ajaxParam.paramData["searchQueryForDisplay"] = searchQueryForDisplay;
	ajaxParam.paramData["CustomHierarchy2"] = facetsSearch();
	ajaxParam.paramData["URL"] = location.href;
	ajaxParam.paramData["pmNameValue"] = pmNameValue;
	ajaxParam.paramData["pmNumberValue"] = pmNumberValue;
	ajaxParam.paramData["pmSeriesValue"] = pmSeriesValue;
	ajaxParam.paramData["seoFriendlyName"] = $('#seoFriendlyName').val();
	ajaxParam.paramData["actualQuery"] = $('#actualQuery').val(); // mis-spelled query
	var promotionList = $('#promotionList').val();
	if(promotionList == ""){
        ajaxParam.paramData["promotionList"] = null;
	}
	else{
	  ajaxParam.paramData["promotionList"] = JSON.parse(promotionList);
	}
	return ajaxParam;
}

/*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,
			null,null,null,true,handleLoadingResult,true,handleLoadingResult,false);
}

/*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,
			null,null,null,true,handleLoadingResult,true,handleLoadingResult,false);
}


// 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('.filter-options-nested');
				tobeSelectedFacet.find('.checkbox').prop('checked',true); // making actual hidden checkbox checked
				tobeSelectedFacet.find('.icheckbox_flat-blue').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('[data-filter="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('.filter-category').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-filters-item').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('data-selected-title',parentTitle).append(title).append($tag);
				$filterList.append(categoryList);
			}
			SCF.initElem($tag);
      }
	$('.applied-filters').show();
	});

}

}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{//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( "outline-color", "" );

});*/
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{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");
}

$("document").ready(function(){
	
	paintWelcomeHeader();
	
	// 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
	});

	$(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)) {

	isUserLoggedIn = true;
	
	//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') {
			userName = profileDetails.lastName+" "+profileDetails.firstName;
			if(cc=='jp'){
				userName=userName+" "+$("#japanSamaCharacterTermbase").val();
			}
			else if(cc=='kr'){
				userName=userName+" "+$("#koreanSamaCharacterTermbase").val();
			}
		} else {
			userName = profileDetails.firstName;
		}
		$userName.html(userName);
		$("#lastName").html(profileDetails.lastName);
		
	}
}


}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{var toronto = {};
toronto.maxIdleTime = chatBotMaxIdle; // pulled from SSC key
toronto.timeOutId = null;
toronto.promptEnabledId = null;
toronto.chatBotProactiveWait = chatBotProactiveWait;
toronto.promptDisabledId = null;
toronto.chatBotProactiveTimeout = chatBotProactiveTimeout;

$(window).on("load", function(){
	if(!isMobileDevice() && screen.width>750) {
		handleHoverText("bind");
	}
	var torontoLaunchedCheck = false;
	if(localStorage.torontoChatLaunched == "true"){
		torontoLaunchedCheck = true;
	}

	if(localStorage.torontoSN != undefined) {
		handleProductContext("compare");
		handleProductContext("save");
	}

	// on load, set/reset proactive prompt related timer
	if(chatBotProactiveTemplates && chatBotProactiveTemplates!="none" && chatBotProactiveTemplates!="" && globalDataLayer.Template!="" &&
	(chatBotProactiveTemplates.indexOf(globalDataLayer.Template)>-1 || chatBotProactiveTemplates.toLowerCase()=="all") 
	&& localStorage.dismissPromptFlag != "true") {
		if(toronto.promptEnabledId) {
			handleProactivePrompt("reset");
		} else {
			handleProactivePrompt("start");
		}
	} else {
		handleProactivePrompt("close");
		handleDisableProactivePrompt("close");
	}

	var pageIdentifierTorontoCheck = false;
	if(templateArray != undefined && (templateArray.indexOf(globalDataLayer.Template) >= 0 || templateArray.indexOf("All") >= 0)) {
		pageIdentifierTorontoCheck = true;
	}

	var tmsLevelTorontoCheck = true;
	if($("#isChatBotRequired").val() != undefined){
		if($("#isChatBotRequired").val() != "yes"){
			tmsLevelTorontoCheck = false;
		}
	}
	
	showHideChatbotWidget(torontoLaunchedCheck, pageIdentifierTorontoCheck, tmsLevelTorontoCheck);
});

$(document).ready(function(){
	if(localStorage.torontoEndTimeStamp != undefined){       				//Checking localStorage timestamp
		var endStampToronto = parseInt(localStorage.torontoEndTimeStamp);
		var currentTimeStamp = new Date().getTime();
		if(currentTimeStamp >= endStampToronto){
			localStorage.removeItem("torontoChatLaunched");
			localStorage.removeItem("expirationTimeWithBuffer");
			localStorage.removeItem("torontoConversationId");
			localStorage.removeItem("torontoConversationStart");
			localStorage.removeItem("torontoChatBotToken");
			localStorage.removeItem("dismissPromptFlag");
			localStorage.removeItem("torontoProductContext");
			localStorage.removeItem("torontoSN");
			localStorage.removeItem("torontoPN");
		}
	}

	$("#chatbotToronto, .chatNotificationBadge").on("click", function(){
		// openChatWindow();
		openChatWindowInNewtab();
	});
	$("#sessionTimeoutClose").on("click tap", function(){
		$("#modalSpinner").hide();
		$('#sessionTimeoutModal').modal('hide');  //close session Timeout pop up for US 194-286
		$("#signOutLinkMob").click();
	});
	$(document).on('keypress', "#sessionTimeoutClose", function(event) { // logic to simulate logout when pop up is closed for US 194-286
		    if (event.keyCode === 13) {
		        $('#sessionTimeoutModal').modal('hide');
		        $("#modalSpinner").hide();
		        $("#signOutLinkMob").click();
		    }
	});
	$("#sessiontimedout_signin").on("click tap", function(){
		$('#sessionTimeoutModal').modal('hide');
		var hostName = window.location.hostname;		//redirecting to HP login and back to the contextual page for US 194-286
		var loginUrl = "https://"+hostName+"/hp-pps-services/auth/login?cc="+getCCLC('cc')+"&lc="+getCCLC('lc')+"&pageUrl="+window.location.href;
		loginUrl = encodeURIComponent(loginUrl);
		var logoutUrl = "https://"+hostName+"/hp-pps-services/auth/logout?cc="+getCCLC('cc')+"&lc="+getCCLC('lc')+"&pageurl="+loginUrl;
		window.location.href = logoutUrl;
	});

	$(".torontoCloseIcon").on("click", function(){
		closeChatWindow();
	});
	
	if(localStorage.torontoChatLaunched == "true" ){
		if(localStorage.expirationTimeWithBuffer){
			startPollingTokenExpiry();
		}
	}

	// 53 - fetch image for mobile from WCM
	fetchWCMChatBotMobileImage();
});

var chatMinimized = true;
var chatMessageCounterOnMinimize = 0;
var chatBotUrl = $("#torontoBotUrl").val(); //"https:///hp-cci-virtualagent.azurewebsites.net";
var chatBotUrlMobile = $("#torontoBotMobileUrl").val();
var chatSessionInHours = $("#torontoBotSessionInHrs").val(); //8;
var chatBotClient = $("#torontoBotClient").val(); // webwidget
var chatBotSubClient = $("#torontoBotSubClient").val(); // webwidget

if(localStorage.torontoChatLaunched == "true"){
	globalDataLayer.chatBotAccessed = true;
}
else{
	globalDataLayer.chatBotAccessed = false;
}

if(localStorage.torontoConversationId != undefined){
	globalDataLayer.conversationId = localStorage.torontoConversationId;
}

var payloadSkeleton = {
   "type":"event",
   "from":{
      "id":"default_userid",
      "name":"User"
   },
   "text":"",
   "name":"contextReceived",   
   "value":{
	   "state" : {
		   "botClient" : chatBotClient,
		   "botSubClient": chatBotSubClient
	   },
      "product":{
         "productOid":"",
         "countryCode":"",
         "languageCode":"",
         "productNumber":"",
         "serialNumber":"",
         "productSeriesOid":""
      },
      "user":{
         "Email":"",
         "FirstName":"",
         "LastName":"",
         "PhoneNumber":""
      },
      "conversationStart":false,
      "GDL":{}
   	}
};

var chatOpenedFirstTimeOnPage = true;
var token = "";

//Global Chat Bot Helper Functions
function openChatWindow(){
	if(localStorage.torontoChatLaunched != "true" || localStorage.torontoProductContext == "true"){
		localStorage.torontoProductContext = false;
		launchChatBot();
	}
	else{
		if(chatOpenedFirstTimeOnPage){
			updateBotData();	
		}	
	}
	chatMessageCounterOnMinimize = 0;
	if($(".chatNotificationBadge").is(":visible")){
		$(".chatNotificationBadge").hide(500);
	}
	$("#torontoChatPage").slideDown(100, function(){
		$("#chatbotToronto").slideUp(100, onChatWindowOpenComplete());
	});

	// 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");
		$("#torontoChatPage").css("height",window.innerHeight+"px");
	}
}

function onChatWindowCloseComplete(){
	console.log("Chat Window is CLOSED now!");
	chatMinimized = true;
	$("#chatbotToronto").focus();
	handleHoverText("bind");
	$("#torontoChatHoverText").addClass("hidden");
}

function showAndUpdateBadge(messageCount){
	if(messageCount > 0){
		$("#accessibility_number_notification").text(messageCount+$("#accessibility_message_notification").text());
		$(".chatNotificationBadge").text(messageCount);
		if(!$(".chatNotificationBadge").is(":visible")){
			$(".chatNotificationBadge").show();
		}
	}
}

function showHideChatbotWidget(chatbotUsed, pageAndLocale, tmsSpecificFlag){
	if(chatbotUsed || (pageAndLocale && tmsSpecificFlag)){
		$("#chatbotToronto").removeClass("hideChatbot");
		$("#torontoChatPrompt").removeClass("hideChatbot");
		$("#torontoChatHoverText").removeClass("hideChatbot");
		globalDataLayer.chatBotWidgetId = "chatbotToronto";
	}
}

function getProductObjForBot(){
	var prodObj = {
        "productOid": globalDataLayer.Product.supportNameOid,
        "countryCode": getCCLC("cc"),
        "languageCode": getCCLC("lc"),
        "productNumber": $("#skuFromSession").val(),
        "serialNumber": $("#serialNumberFromSession").val(),
        "productSeriesOid": globalDataLayer.Product.seriesOid
    }
    return prodObj;
}

function launchChatBot(){
	showLoadingSpinner();
	console.log("BOT LAUNCHING");
	//Gets chat token, and sends the GDL, conversation ID and conversationStart
	var launchPayload = $.extend(true, {}, payloadSkeleton);
	launchPayload.value.conversationStart = true;
	launchPayload.value.product = getProductObjForBot();
	
	var windowObjectReference;
	var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";
	windowObjectReference = window.open("http://www.support.hp.com/", "HP_WindowName", strWindowFeatures);



	launchPayload.value.GDL = globalDataLayer;


	$.ajax({
		type: 'POST',
	    url: "/hp-pps-services/bot/authenticatebot",
	    contentType: "application/json",
	    dataType: 'json',
	    data: JSON.stringify(launchPayload)
	}).done(function(data){
		//on success
		var chatSessionInMilliseconds = parseFloat(chatSessionInHours) * 3600000;
		/********************MAINTAINING TIMESTAMP TO EXPIRE LOCAL STORAGE**************************/
		var torontoStartStamp = new Date().getTime();
		var torontoLaunchSessionEndStamp = parseInt(torontoStartStamp) + parseInt(chatSessionInMilliseconds);  //Keeping localStorage timestamp expiry for 8hrs.
		localStorage.torontoStartTimeStamp = torontoStartStamp;
		localStorage.torontoEndTimeStamp = torontoLaunchSessionEndStamp;
		/*******************************************************************************************/

		chatOpenedFirstTimeOnPage = false;
		localStorage.torontoChatLaunched = true;
		localStorage.torontoConversationStart = true;
		localStorage.torontoConversationId = data.conversationId;
		localStorage.torontoChatBotToken = data.token;

		globalDataLayer.conversationId = data.conversationId;
		loadChatBotIframe(data.token);
		setTokenBuffer(parseInt(data.expires_in));
		startPollingTokenExpiry();
		
	}).fail(function(jqXHR, textStatus){
		console.log("!!!!!!!!Launch service failed!!!!!!!!!!!");
		hideLoadingSpinner();
		showChatbotUnavailable();
	});
}

//Global Chat Bot In Newtab Functions

function openChatWindowInNewtab(){
	var windowObjectReference;
	var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";
	var countryCode =  getCCLC("cc");
    var languageCode = getCCLC("lc");
	var serialNumber = $("#serialNumberFromSession").val();
	var chatBotUrl = $("#torontoBotUrl").val(); //"https:///hp-cci-virtualagent.azurewebsites.net";
	var chatBotUrlMobile = $("#torontoBotMobileUrl").val();
	var BotSubClient = $("#torontoBotSubClient").val();
	var template = globalDataLayer.Template ? globalDataLayer.Template :'';
	var query = globalDataLayer.Document.TMSCategorization ? globalDataLayer.Document.TMSCategorization.substring(0,500): ''; 
	var PL = globalDataLayer.Product.productLineCode ? globalDataLayer.Product.productLineCode:'';
	var ProductNumber = $("#skuFromSession").val();
	var ProductNameOID = globalDataLayer.supportNameOid ? globalDataLayer.supportNameOid :'';
	var ProductSeriesName = globalDataLayer.Product.bigSeriesName ? globalDataLayer.Product.bigSeriesName :'';
	var ProductSeriesNameOID =  globalDataLayer.Product.seriesOid  ? globalDataLayer.Product.seriesOid : '';
	var ProductName = globalDataLayer.Product.seriesName ? globalDataLayer.Product.seriesName :'';
	
	if(isMobileDevice()) {
		chatBotUrlForNewtab = chatBotUrlMobile;
	} else {
		chatBotUrlForNewtab = chatBotUrl;
	}
	windowObjectReference = window.open(encodeURI(chatBotUrlForNewtab+"&BotSubClient="+BotSubClient+"&Template="+template+"&query="+query+"&SerialNumber="+serialNumber+"&PL="+PL+"&ProductNumber="+ProductNumber+"&ProductName="+ProductName+"&ProductNameOID="+ProductNameOID+"&ProductSeriesName="+ProductSeriesName+"&ProductSeriesNameOID="+ProductSeriesNameOID+"&CC="+countryCode+"&LC="+languageCode, "Toronto_WindowName", strWindowFeatures));
	globalDataLayer.chatBotAccessed = true;
}


function updateBotData(){
	showLoadingSpinner();
	console.log("UPDATE BOT HAPPENING");
	var torontoChatPayload = $.extend(true, {}, payloadSkeleton);
	//Ajax call to update bot with GDL, conversation ID and conversationStart goes here
	torontoChatPayload.value.conversationStart = false;
	torontoChatPayload.value.product = getProductObjForBot();
	torontoChatPayload.value.GDL = globalDataLayer;

	$.ajax({
		type: 'POST',
	    url: "/hp-pps-services/bot/sendbotactivity?token="+localStorage.torontoChatBotToken+"&id="+localStorage.torontoConversationId,
	    contentType: "application/json",
	    dataType: 'json',
	    data: JSON.stringify(torontoChatPayload)
	}).done(function(data){
		// on success
		//Chat has launched because of launchChatBot() hence localStorage.torontoChatLaunched = true; and localStorage.torontoConversationStart = true;
		
		//**********************
		// globalDataLayer.conversationId = conversationID;
		//**********************
		chatOpenedFirstTimeOnPage = false;
		loadChatBotIframe(localStorage.torontoChatBotToken);
		
	}).fail(function(jqXHR, textStatus){
		console.log("!!!!!!!!Update service failed!!!!!!!!!!!");
		if($(".torontoChatBotIframe").is(":visible")){
			$(".torontoChatBotIframe").addClass("hideChatbot");
		}
		hideLoadingSpinner();
		showChatbotUnavailable();
	});
}

function refreshToken(){
	//AJAX CALL TO REFRESH TOKEN

	$.ajax({
		type: 'POST',
	    url: "/hp-pps-services/bot/refreshchatbottoken?token="+localStorage.torontoChatBotToken,
	    contentType: "application/json",
	    dataType: 'json'
	}).done(function(data){
		//on success
		if(data.token != null && localStorage.torontoChatBotToken != data.token){
			localStorage.torontoChatBotToken = data.token;
			$(".torontoChatBotIframe").addClass("hideChatbot");
			$("#torontoChatPrompt").addClass("hideChatbot");
			$("#torontoChatHoverText").addClass("hideChatbot");
			showLoadingSpinner();
			loadChatBotIframe(data.token);
		}

		if(data.conversationId != null && localStorage.torontoConversationId != data.conversationId){
			localStorage.torontoConversationId = data.conversationId;
			globalDataLayer.conversationId = data.conversationId;
		}

		if(data.expires_in != null){
			setTokenBuffer(parseInt(data.expires_in));
			startPollingTokenExpiry();
		}

	}).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){
		chatMessageCounterOnMinimize += 1;
		showAndUpdateBadge(chatMessageCounterOnMinimize);
	}
}

function botStartOver(){
	console.log("<==========================START OVER YES==========================>");
	console.log("START OVER BOT HAPPENING");
	var startOverPayload = $.extend(true, {}, payloadSkeleton);
	//Ajax call to update bot with GDL, conversation ID and conversationStart goes here
	startOverPayload.value.conversationStart = true;
	startOverPayload.value.product = getProductObjForBot();
	startOverPayload.value.GDL = globalDataLayer;
	//AJAX CALL TO START OVER 

	$.ajax({
		type: 'POST',
	    url: "/hp-pps-services/bot/sendbotactivity?token="+localStorage.torontoChatBotToken+"&id="+localStorage.torontoConversationId,
	    contentType: "application/json",
	    dataType: 'json',
	    data: JSON.stringify(startOverPayload)
	}).done(function(data){
		// on success
		
	}).fail(function(jqXHR, textStatus){
		console.log("!!!!!!!!Start over service failed!!!!!!!!!!!");
		$(".torontoChatBotIframe").addClass("hideChatbot");
		$("#torontoChatPrompt").addClass("hideChatbot");
		$("#torontoChatHoverText").addClass("hideChatbot");
		showChatbotUnavailable();
	});
}

// R182-70  handle setting, resetting and closing of timer
function handleTorontoTimer(state) {
	//set the checkTime flag and start the timer
	if(state == "start") {
		toronto.timeOutId = setTimeout(function(){ 
			$(".torontoCloseIcon").click(); 
		}, 
		toronto.maxIdleTime*1000);	
	}
	//close the timer
	else if(state == "close") {
		clearTimeout(toronto.timeOutId);
	}
	//reset the timer
	else if(state == "reset") {
		$.when(handleTorontoTimer("close")).then(handleTorontoTimer("start"));
	}
}

// R182-69  handle saving, retrieving product context and detecting change
function handleProductContext(state) {
	if(state == "save") {
		var product = fetchProductInformation();
		localStorage.torontoSN = product.SN;
		localStorage.torontoPN = product.PN;
		
	} else if(state == "compare") {
		var product = fetchProductInformation();
		//product context change if localstorage SN and PN do not match with current SN and PN
		if(localStorage.torontoSN != product.SN || localStorage.torontoPN != product.PN) {
			localStorage.torontoProductContext = true;
			localStorage.torontoConversationId = "";
			globalDataLayer.conversationId = "";
		}
	}	
}

function fetchProductInformation() {
	var currentUrl = window.location.href;
	var urlArray = currentUrl.split("/");
	var product = {};
	if(currentUrl.indexOf("model")>-1) {
		// page contextual at product level
		product.SN = urlArray[urlArray.length-3];
		product.PN = urlArray[urlArray.length-1];
	} else {
		//lastUrlInfo will be a number in case of page contextual at series level
		var lastUrlInfo = urlArray[urlArray.length-1];
		if(isNaN(lastUrlInfo)) {
			product.SN = 0;
			product.PN = 0;
		} else {
			product.SN = lastUrlInfo;
			product.PN = 0;
		}
	}
	return product;
}

// R182-53  handle setting, resetting and closing of enabling proactive prompt timer
function handleProactivePrompt(state) {
	//start the timer
	if(state == "start") {	
		toronto.promptEnabledId = setTimeout(function(){ 
			// unbind hover text
			handleHoverText("unbind");
			// show proavtive prompt
			$("#torontoChatPrompt").removeClass("hidden"); 
			$("#torontoChatPrompt").attr("aria-hidden",false);
			// start the dismissing timer
			handleDisableProactivePrompt("start");
			//close the showing proactive timer time
			handleProactivePrompt("close");
		}, 
		toronto.chatBotProactiveWait*1000);	
	}
	//close the timer
	else if(state == "close") {
		if(toronto.promptEnabledId!=null) {
			clearTimeout(toronto.promptEnabledId);
		}
	}
	//reset the timer
	else if(state == "reset") {
		handleProactivePrompt("start");
		handleProactivePrompt("close");
	}
}

// R182-53  handle setting, resetting and closing of disabling proactive prompt timer
function handleDisableProactivePrompt(state) {
	//start the timer
	if(state == "start") {	
		toronto.promptDisabledId = setTimeout(function(){ 
			handleHoverText("bind");
			$("#torontoChatPrompt").addClass("hidden"); 
			$("#torontoChatPrompt").attr("aria-hidden",true);
			// close the dismissing timer
			handleDisableProactivePrompt("close");
			//start the showing proactive timer time
			handleProactivePrompt("start");
		}, 
		toronto.chatBotProactiveTimeout*1000);	
	}
	//close the timer
	else if(state == "close") {
		if(toronto.promptDisabledId!=null) {
			clearTimeout(toronto.promptDisabledId);
		}
	}
	//reset the timer
	else if(state == "reset") {
		handleDisableProactivePrompt("start");
		handleDisableProactivePrompt("close");
	}
}

function dismissChatPrompt(event) {
	// hide the prompt
	$("#torontoChatPrompt").addClass("hidden");
	// disable timers
	handleProactivePrompt("close");
	handleDisableProactivePrompt("close");
	//set dismissPromptFlag, so that user is not prompt in the same session
	localStorage.dismissPromptFlag = true;
	handleHoverText("bind");
	if(event) event.stopPropagation();
}

function fetchWCMChatBotMobileImage() {
	$.ajax({
		type: "GET",
        url: "/hp-pps-services/webcontent/image/url",
        data:{
            "sitearea": "all-pages/chat-bot",
            "component": "image-component"
        },
        dataType: "json",
        beforeSend: function(xhr) {
            xhr.setRequestHeader('Content-Type', 'application/json');
        }
	}).done(function(data){
		$("#botMobileImage").attr("src",data);
	}).fail(function(jqXHR, textStatus){
		console.log("fail - fetch mobile chatbot img from WCM");
		$("#botMobileImage").attr("src",$("#botImage").attr("src"));
	});
}

function isMobileDevice(){
    var mobileDevices = ["Android", "iPad", "iPhone"];
    var currentDevice = isMobile.any();
    currentDevice = currentDevice == null ? "" : currentDevice[0];
    return $.inArray(currentDevice, mobileDevices) != -1;
}

function handleHoverText(state) {
	if(state == "bind") {
		$("#chatbotToronto").on("mouseenter",function() {
			$("#torontoChatHoverText").removeClass("hidden");
			dismissChatPrompt();
		});
		$("#chatbotToronto").on("mouseleave",function() {
			$("#torontoChatHoverText").addClass("hidden");
		});
		
	} else if(state == "unbind") {
		$("#chatbotToronto").off("mouseenter mouseleave");
	} 
}  
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{var vids = [];		//array to store the player objects alm# 2635
var jsonVideoData;
var docVideoData = [];
var widgetAPIUrl = $("#widgetApiUrl").val();		//get the values from SSC
var iframeApiUrl = $("#iframeApiUrl").val();
var brightCoveCountryCodes = $("#brightCoveVideoLocales").val();  //from SSC ALM# 2635
var counter = 0;
var item = {};
var docVideoCount = 0;
var jsonVideoDataCounter = 0;
var youtubeScriptCalled = false;

$(document).ready(function() { 
	if(widgetAPIUrl == undefined || widgetAPIUrl == null || widgetAPIUrl == ""){				//null checks for SSC keys ALM# 2635
		widgetAPIUrl = "https://s.ytimg.com/yts/jsbin/www-widgetapi-vfl6tgGSV/www-widgetapi.js";
	}
	if(iframeApiUrl == undefined || iframeApiUrl == null || iframeApiUrl == ""){
		iframeApiUrl = "https://www.youtube.com/iframe_api";
	}
	if(brightCoveCountryCodes != undefined && brightCoveCountryCodes != null && brightCoveCountryCodes != "" && !Array.isArray(brightCoveCountryCodes)){		//adding isArray check to validate if already split.
		brightCoveCountryCodes = brightCoveCountryCodes.split(",");		//creating an array
	}

	//ALM-3146 - inserting the youtube frame only when the locale is not cn

	if ($.inArray(getCCLC("cc"),brightCoveCountryCodes) == -1) {
		$("a[id*=video], a.videoThumbnail, [data-playlist-id] a").on("mouseover", function() {
			var firstScriptTag = document.getElementsByTagName('script')[0];
			if (!youtubeScriptCalled && firstScriptTag && firstScriptTag.getAttribute('src') != iframeApiUrl) {
				youtubeScriptCalled = true;
				var tag = document.createElement('script');		//insert the youtube iframe script ALM# 2635
				tag.src = iframeApiUrl;
				firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
			}
		});
	}

	$(document).on('hidden.bs.modal', '.modal.playlistVideoModal', function() {
		$(this).find(".vjs-playing").trigger("click");
		if(openVideoModalId != ""){
			$("a[data-target='#"+openVideoModalId+"']").focus();
			openVideoModalId = "";
		}
		if($(this).parent().find("iframe").length != 0){		//pause youtube video ALM# 2635
			var iframeID = $(this).find("iframe").attr("id");
			for(var k=0;k<vids.length;k++){
				if(vids[k].f != undefined && vids[k].f != null){
					if (iframeID == vids[k].f.id)  {  
						vids[k].pauseVideo();
						break;
					}
				}
			}
		}
	});

	$(".pageLevelPlaylist").each(function(index, value){
		fetchPlaylist($(this).data("playlist-id"), 4);
	});

	/** ALM - 3423 - Fix for Topic-to-topic links failing from documents opened from PDP */
	/** ALM - 3501 - Added fix to not update the URL for alerts */
	if(window.location.href.search('/product') > -1 && window.location.href.search('/document') > -1  && window.location.href.search('ish') > -1){
		var requestUrl = window.location.href;
		var arrParam = requestUrl.split('/');
		var modHostUrl=arrParam[0]+'//'+arrParam[2]+'/'+arrParam[3]+'/';
		console.log(modHostUrl);
		
		$('#udpDocumentFragment a[href*="ish_"]').each(function(index,val) {        
			var ishLink=val.href;
			console.log(ishLink);
			var str = ishLink.split("/");
			if(ishLink == -1 || str.length >= 7){
				var modres = str[7].split("?");
				console.log(modres);
				if(modres.indexOf('document')){
					val.href = modHostUrl+ 'document/' +modres[0];
					console.log(val.href);
				}
			}
		});
	} else if(window.location.href.search('/document') > -1  && window.location.href.search('ish') > -1){
		var requestUrl = window.location.href;
		var arrParam = requestUrl.split('/');
		var modHostUrl=arrParam[0]+'//'+arrParam[2]+'/'+arrParam[3]+'/'+arrParam[4]+'/';
		console.log(modHostUrl);

		$('#udpDocumentFragment a[href*="ish_"]').each(function(index,val) {        
				var ishLink=val.href;
				var str = ishLink.split("/");
				if(str.length >= 7){
					var modres = str[7].split("?");
					val.href = modHostUrl + modres[0];
					console.log(val.href);
				}
		});
	}
	/** ALM - 3501 - Fx ends here */
	/** ALM - 3423 - Fix for Topic-to-topic links failing from documents opened from PDP ends here */
	/** Jira ID #WCCWSCR-203 - Fix for inline wise document links update */
	if(window.location.href.search('/document') > -1  && window.location.href.search('ish') > -1){
		var requestUrl = window.location.href;
		var arrParam = requestUrl.split('/');
		var modHostUrl=arrParam[0]+'//'+arrParam[2]+'/'+arrParam[3]+'/'+arrParam[4]+'/';
		console.log(modHostUrl);

		$('#udpDocumentFragment a').filter(function(index, element) {
			var href = $(element).attr('href');
			return href.includes("/wise") && href.includes("/document");
		}).each(function(index, val) {        
				var ishLink=val.href;
				var str = ishLink.split("/");
				if(str.length >= 5){
					val.href = modHostUrl + str[5];
					console.log(val.href);
				}
		});
	}
	/** Jira ID #WCCWSCR-203 - Fix for inline wise document links update ends here */
});
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

$(document).trigger("pageLoaded");  //Custom Event trigger that is being listened to, in microsite.js as part of ALM 1873


//function to fetch video playlist ALM# 2635
function fetchPlaylist(playlistId, numberOfVideosPerPage){
	playlistId = parseInt(playlistId);
	playlistMasterObject[playlistId] = {};
	var cc = getCCLC("cc");
	var lc = getCCLC("lc");
	// var numberOfVideosPerPage = $("div[data-playlist-id='"+playlistId+"']").data("perPage");
	//Ajax call goes here

	$.ajax({
		type: 'GET',
		url: "/hp-pps-services/videos/playlist/"+playlistId+"/cc/"+cc+"/lc/"+lc,
		contentType: "application/json",
		dataType: 'json'
	}).done(function(data){
		if(twoBoxExperienceCheck){
			$(".simple-solution").hide();
			twoBoxExpHideVideoSection = true;
		}else{
			if(data != undefined && data != null && 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())/perPage);
			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('.pagination-less').addClass('disabled');
			playlistWrapperContext.find('.pagination-more').attr('disabled','disabled');
			playlistWrapperContext.find('.pagination-more').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())/perPage; 
			curPage++;
			response(copyofjsonData, "false", playlistContext, curPage);
		});
	}




	var perPage= playlistMasterObject[playlistId].perPage;
	// var curPage= 1;
	var copyofjsonData;
	var modalGlobal = "";
	var youtubeFlag = false;
	var countryCode = getCCLC("cc");
	if($.inArray(countryCode,brightCoveCountryCodes) != -1){
		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 + '<div class="modal playlistVideoModal fade" id="video-modal'+videoId+'" tabindex="-1" role="dialog" aria-label="HP Videos" aria-hidden="true" data-show="true"><div class="modal-dialog modal-md"><div id="data-collection" class="modal-content"><div class="embed-container"><video style="width: 100%; height: 100%; position: absolute; top: 0px; bottom: 0px; right: 0px; left: 0px;" data-video-id="'+videoId+'" data-account="'+accountId+'" data-player="'+playerId+'" data-embed="default" class="video-js" controls="" poster="'+videoPoster+'"></video><\/div><div class="modal-body"><div class="hp-row"><div class="col-lg-24"><button type="button" class="button button-block primary fr" data-dismiss="modal">'+$("#video_close").val()+'<\/button><h3 class="no-subtitle">'+videoName+'<\/h3><p>'+videoDescription+'<\/p><\/div><\/div><\/div><\/div><\/div><\/div>\n';
		}
	}else {												//checking if brightCove or youTube video needs to be rendered ALM# 2635
		youtubeFlag = true;
		jsonVideoData = jsonData;
		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 + '<div class="modal playlistVideoModal fade" id="video-modal'+videoId+'" tabindex="-1" role="dialog" aria-label="HP Videos" aria-hidden="true" data-show="true"><div class="modal-dialog modal-md"><div id="data-collection" class="modal-content"><div class="embed-container"><div style="width: 100%; height: 100%; position: absolute; top: 0px; bottom: 0px; right: 0px; left: 0px;" class="video-js" id="player'+i+'" ></div><\/div><div class="modal-body"><div class="hp-row"><div class="col-lg-24"><button type="button" class="button button-block primary fr" data-dismiss="modal">'+$("#video_close").val()+'<\/button><h3 class="no-subtitle">'+videoName+'<\/h3><p>'+videoDescription+'<\/p><\/div><\/div><\/div><\/div><\/div><\/div>\n';
		}
	}
	$("body").append(modalGlobal);
	if(youtubeFlag){
		$.getScript(widgetAPIUrl).done(function( script, textStatus ) {
			console.log( textStatus );
		})
		.success(function(textStatus){
			console.log("in success");
			jsonVideoDataCounter = 0;
			onYouTubeIframeAPIReady();		//if youtube flag is true only then invoke the player API ALM# 2635				
		})

	}



	if($("#pageIdentifier").val() != "HP Microsite"){
		loadBrightcoveScriptForVideos();
	}

	function renderPagination(page,jsonData, videoContainerReference) {
		var videoContainerMainWrapper= videoContainerReference.parent(".videoPlaylistWrapper");
		startonPage = page * perPage - (perPage -1);
		lastonPage = startonPage + (perPage - 1);
		if (startonPage == 1) {
			// disable prev button
			videoContainerMainWrapper.find('.pagination-less').attr('disabled','disabled');
			videoContainerMainWrapper.find('.pagination-less').addClass('disabled');
		} else {
			videoContainerMainWrapper.find('.pagination-less').removeAttr('disabled');
			videoContainerMainWrapper.find('.pagination-less').removeClass('disabled');
		}

		if (lastonPage >= jsonData.length) {
			// disable next button
			videoContainerMainWrapper.find('.pagination-more').attr('disabled','disabled');
			videoContainerMainWrapper.find('.pagination-more').addClass('disabled');
		} else {
			videoContainerMainWrapper.find('.pagination-more').removeAttr('disabled');
			videoContainerMainWrapper.find('.pagination-more').removeClass('disabled');
		}							 
	}

	function response(jsonData, showall, videoPlaylistContext, curPage) {
		if(videoPlaylistContext === undefined){
			var videoContainerReference = $("div[data-playlist-id='"+playlistId+"']");
		}
		else{
			var videoContainerReference = videoPlaylistContext;
		}
		var videoContainerMainWrapper= videoContainerReference.parent(".videoPlaylistWrapper");
		copyofjsonData = jsonData;	
		renderPagination(curPage,jsonData, videoContainerReference);
		renderVideos(jsonData, showall, videoContainerReference);
		$('.videoContent figcaption').matchHeight();

		//for truncating the video description 
		var truncVal = 100; 
		if($('#truncationLimit').length > 0){
			truncVal = parseInt($('#truncationLimit').val());
		}

		videoContainerMainWrapper.find("figcaption").children("span").each (function () {
			if ($(this).text().length > truncVal)
				$(this).text($(this).text().substring(0,truncVal) + '...');
		});

		videoContainerMainWrapper.find('.play').each(function() {
			$(".videoContent img").load(function(){
				var topPos = ($(".videoContent img").innerHeight()-36)/2;
				$('.play').css("top", topPos);

				var leftPos = ($(".videoContent").outerWidth() - 48)/2;
				$('.play').css("left", leftPos);
			});
		}); 
	}

	fillPagination = function(objectInReference, pageSize, jsonData) {
		var pageTotalVal;
		var endVal;
		var startVal;
		var startValLocation = objectInReference.find('.paginationStartVal');
		var endValLocation = objectInReference.find('.paginationEndVal');
		var totalValLocation = objectInReference.find('.paginationTotalVal');

		if (null != jsonData)
			pageTotalVal = jsonData.length;
		else
			pageTotalVal = "";

		if (pageTotalVal < pageSize) {
			endVal = pageTotalVal;
		} else {
			endVal = pageSize;
		}

		startValLocation.html('1');
		endValLocation.html(endVal);
		totalValLocation.html(pageTotalVal);
	};

	updatePagination = function(objectInReference, jsonData, pageStartVal, pageEndVal) {

		var pageTotalVal;
		var startValLocation = objectInReference.find('.paginationStartVal');
		var endValLocation = objectInReference.find('.paginationEndVal');
		var totalValLocation = objectInReference.find('.paginationTotalVal');

		if (null != jsonData){
			pageTotalVal = jsonData.length;
		}
		else
			pageTotalVal = "";

		startValLocation.html(pageStartVal);
		endValLocation.html(pageEndVal);
		totalValLocation.html(pageTotalVal);
	};


	function renderVideos(jsonData, showall, videoContainerReference) {
		var videoContainerMainWrapper= videoContainerReference.parent(".videoPlaylistWrapper");
		videoContainerReference.empty();

		var str = "";
		// var modal = "";

		if (jsonData.length > lastonPage) {
			upperLimit = lastonPage; 
			videoContainerMainWrapper.find('.pagination-container').show();
		} else {
			upperLimit = jsonData.length;
			// code to disable next goes here
			//$('.pagination-container').hide();

		}

		if(showall == 'true'){

			startonPage =1;
			upperLimit = jsonData.length;
			videoContainerMainWrapper.find('.pagination-less').attr('disabled','disabled');
			videoContainerMainWrapper.find('.pagination-less').addClass('disabled');
			videoContainerMainWrapper.find('.pagination-more').attr('disabled','disabled');
			videoContainerMainWrapper.find('.pagination-more').addClass('disabled');

		}

		for (var i=(startonPage - 1); i<upperLimit; i++) {
			// var title = jsonData[i];
			var title = jsonData[i].description;
			var videoId = jsonData[i].id;
			var videoThumbnail = jsonData[i].images.thumbnail;
			var videoPoster = jsonData[i].images.poster;
			var videoName = jsonData[i].name;
			var videoDescription = jsonData[i].description;

			if(parseInt(playlistMasterObject[playlistId].perPage) == 4){
				str = str + '<div class="col-lg-6 col-md-12 col-sm-24 videoContent">' + '<a aria-describedby="videoCaption'+i+'" class="modal-trigger" href="javascript:void(0)" data-toggle="modal" data-backdrop="static" data-target="#video-modal'+videoId+'">' + '<img style="cursor: pointer;clear:both;display:block;" src="' + videoPoster + '"><span title=\"play\" rel=\"\" class=\"play js_video_trigger\"><\/span></a>'  + '<figcaption id="videoCaption'+i+'"><strong> '+videoName+' </strong> <span>'+videoDescription+'</span> </figcaption></div>';
			}
			else{
				str = str + '<div class="col-lg-8 col-md-12 col-sm-24 videoContent">' + '<a aria-describedby="videoCaption'+i+'" class="modal-trigger" href="javascript:void(0)" data-toggle="modal" data-backdrop="static" data-target="#video-modal'+videoId+'">' + '<img style="cursor: pointer;clear:both;display:block;" src="' + videoPoster + '"><span title=\"play\" rel=\"\" class=\"play js_video_trigger\"><\/span></a>'  + '<figcaption id="videoCaption'+i+'"><strong> '+videoName+' </strong> <span>'+videoDescription+'</span> </figcaption></div>';
			}
		}

		videoContainerReference.append(str);
		// videoContainerReference.append(modal);

		fillPagination(videoContainerMainWrapper.find('containerForPaginationHead'), perPage, jsonData);
		updatePagination(videoContainerMainWrapper.find('containerForPaginationHead'), jsonData, startonPage, upperLimit);	
		fillPagination(videoContainerMainWrapper.find('.containerForPaginationFoot'), perPage, jsonData);
		updatePagination(videoContainerMainWrapper.find('.containerForPaginationFoot'), jsonData, startonPage, upperLimit);
	}
	response(jsonData, "false", undefined, 1);
}

$(".bcSingleVideoContainer").each(function(index, val){
	var actualVideoId = $(this).attr("id");
	if(actualVideoId.indexOf(":") >= 0){
		$(this).attr("id", $(this).attr("id").replace(":", ""));
	}
	$(this).attr("data-id", $(this).attr("id"));

	var collectionID = actualVideoId;
	fetchVideo($(this).data("id"), collectionID);			//make call to fetch youtube video ALM# 2635

});

//Fetch video details ALM# 2635
function fetchVideo(videoThNWrapperId, collectionID){
	var cc = getCCLC("cc");
	var lc = getCCLC("lc");
	var docSource= $("#docSource").val();
	var docLanguage=$("#docLanguage").val();
	console.log("docLanguage is===>"+docLanguage);
	var udpFlag='';
	if(docLanguage!=undefined && docLanguage!=null && docLanguage!=''){
		if(docLanguage == "zh" | docLanguage == "zh-hans" || docLanguage == "zh-hant"){
			docLanguage="zhcn";
		}
		lc=docLanguage;
	}
	if(docSource!=undefined && docSource!=null && docSource!='' && docSource == 'UDP'){
		udpFlag=true;
	}else{
		udpFlag=false;
	}
	docVideoCount++;			//checking the number of videos in a document ALM# 2635
	$.ajax({
		type: 'GET',
		url: "/hp-pps-services/videos/collection/"+collectionID+"/cc/"+cc+"/lc/"+lc+"/udpFlag/"+udpFlag,
		contentType: "application/json",
		dataType: 'json'
	}).done(function(data){
		if(data != undefined && data != null && data != ""){
			// on success
			var source = $("#singleVideoTemplate").html();
			var template = Handlebars.compile(source);
			$('.bcSingleVideoContainer[data-id="'+videoThNWrapperId+'"]').html(template(data));
			//if($.inArray(cc,brightCoveCountryCodes) == -1){
			if(data[0].streamingService=="YouTube"){
				$('.bcSingleVideoContainer').find("video").parent().append("<div style='width: 100%; height: 100%; position: absolute; top: 0px; bottom: 0px; right: 0px; left: 0px;' id='player"+counter+"'></div>")
				$('.bcSingleVideoContainer').find("video").remove();
				var item = {};
				item["youtube_id"] = data[0].youtube_id;
				item["youtube_url"] = data[0].videoURL;
				if(data[0].lang_code != undefined && data[0].lang_code != "" && data[0].lang_code != null){
					item["lang_code"] = data[0].lang_code;		//assigning the fallback langcode ALM# 2635
				}else{
					item["lang_code"] = "";				//setting the default lang code as empty if not fallback video 
				}
				docVideoData.push(item);
				counter++;
				if(docVideoCount == $(".bcSingleVideoContainer").length){
					$.getScript(widgetAPIUrl).done(function( script, textStatus ) {
						console.log( textStatus );
					})
					.success(function(textStatus){
						console.log("in success");
						jsonVideoDataCounter = 0;
						jsonVideoData = docVideoData;
						onYouTubeIframeAPIReady();		//invoke the player API function			
					})
				}
			}//end of if loop
		}

	}).fail(function(jqXHR, textStatus){

	});
}

var brightcoveScriptCalled = false;
$(document).on("click", ".videoThumbnail", function(){
	if(!brightcoveScriptCalled){
		loadBrightcoveScriptForVideos();
		brightcoveScriptCalled = true;
	}
});

/*
 * 19.4 CRs - ALM 2221
 */
/*
 *	$(window).on("load", function(){
		if($("#pageIdentifier").val() == "HP Microsite"){
			loadBrightcoveScriptForVideos();
		}
	});

 */

function loadBrightcoveScriptForVideos(){
		$("body").append("<script type='text/javascript' src='"+window.location.protocol+"//players.brightcove.net/"+accountId+"/"+playerId+"_default/index.min.js'></script>");
}

/* youtube api function ALM# 2635  */

function onYouTubeIframeAPIReady() {
	var langCode = "";
	if(jsonVideoData != undefined && jsonVideoData != ""){
		if(jsonVideoDataCounter > 0){
			jsonVideoData = "";		//avoid the function being called twice
		}
		for(var j=0;j<jsonVideoData.length;j++){
			player = "player"+j;
			player = new YT.Player("player"+j, {
				videoId: jsonVideoData[j].youtube_id,
				events: {}
			});
			/*US-133297 Youtube URL Changes*/
			if(jsonVideoData[j].youtube_url !=undefined && jsonVideoData[j].youtube_url != "" && jsonVideoData[j].youtube_url !=null)
				{
				$("iframe#player"+j).attr("src",jsonVideoData[j].videourl);
				}
			else{
			if(jsonVideoData[j].lang_code != undefined && jsonVideoData[j].lang_code != "" && jsonVideoData[j].lang_code != null){
				langCode = jsonVideoData[j].lang_code;			//check if the fallback langCode is empty or not and assign it.
			}else{	
				if(youtubeCCLCMap != null && youtubeCCLCMap != "" && youtubeCCLCMap != undefined){		//check if the cclcMap is available.
					if(!jsonVideoDataCounter > 0 && typeof youtubeCCLCMap != "object"){			//to avoid multiple parsing of the json object
						youtubeCCLCMap = JSON.parse(youtubeCCLCMap);	
					}
					langCode = youtubeCCLCMap[getCCLC("cc")+"-"+getCCLC("lc")];
					if(langCode == undefined){
						langCode = en;			//default to en if the cclc combination does not exist.
					}
				}else{
					langCode = en;				//default to en if the cclcmap SSC key is not available.
				}

			}
			var youtubePlayerURL = $("iframe#player"+j).attr("src");
			youtubePlayerURL = youtubePlayerURL + '&rel=0&hl='+langCode;
			$("iframe#player"+j).attr("src",youtubePlayerURL);
			}
			vids.push(player);
			jsonVideoDataCounter++;
		}
	}

} //end of function

Handlebars.registerHelper({
	getHiddenFieldValues: function(hidden_field_id){        
		return $("#"+hidden_field_id).val();
	}
});

$(document).on('hidden.bs.modal', '.modal.singleVideoModal', function() {
	// Pause the video when modal in document page is closed
	var videoId = $(this).find("video").attr("id");
	if(videoId != undefined){
		videojs(videoId).pause();
	}
	if($(this).parent().find("iframe").length != 0){		//pause youtube video ALM# 2635
		var iframeID = $(this).find("iframe").attr("id");
		for(var k=0;k<vids.length;k++){
			if(vids[k].f != undefined && vids[k].f != null){
				if (iframeID == vids[k].f.id)  {  
					vids[k].pauseVideo();
					break;
				}
			}
		}
	}
});
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{var globalDeviceObject = {};
var personalDevicePNSNArr = [];
// (function(){

// $("#modalLoginBtn").on("click", loginCallHpsa);
// // })();
if(typeof profileDetails !== 'undefined' && profileDetails){
	if(profileDetails.loggedIn == true){
		
		// If the user is registering from EAS or Contact HP
		if (localStorage.productToBeAddedFlag) {
			
			// try adding the device only if the details are valid
			if(localStorage.serialNumber && localStorage.productNumber){
				addDeviceInfoPostRegistration();
			}
			
		} else {
			fetchAllDevices(profileDetails.profileType);
		}
			if(profileDetails.profileType == "CONSUMER"){
				globalDataLayer.customerState = "Personal";
			}
			else if(profileDetails.profileType == "COMMERCIAL"){
				globalDataLayer.customerState = "Business";
			}
			else{
				globalDataLayer.customerState = profileDetails.profileType;
			}
			if($("#pageIdentifier").val() == "Contact HP - Anonymous"){
				var errorCodePresent = false;
				var statusCode;
				errorCodePresent = (globalDeviceObject.ErrorItem!= undefined)? true : false;
				if(errorCodePresent){
					statusCode = globalDeviceObject.ErrorItem.statusCode;
					if(statusCode == 'SERVICE_ERROR'){
						// go to step 2 directly in case service is down
						showLoggedInView();
					}
					else{
						$('#masterDiv').removeClass('hide');
					}
				}
				// else{
				// 	$('#masterDiv').removeClass('hide');
				// }
			}
	}
	else{
		globalDataLayer.customerState = "Anonymous";
	}
}
else{ //not logged in view
	globalDataLayer.customerState = "Anonymous";
        if($("#pageIdentifier").val() == "Dashboard"){
                paintSessionTimedOutView();
        }
        else if($("#pageIdentifier").val() == "Add Device") {
                window.location.href = "/"+getCCLC("cc")+"-"+getCCLC("lc")+"/dashboard";
        }
		else if($("#pageIdentifier").val() == "Contact HP - Anonymous") {
			$('#masterDiv').removeClass('hide');
			var currentURL = window.location.href;
			if(currentURL.indexOf("contact-hp")>-1) {
				$(".sign-in-guest").removeClass("hide");
			}
        }
}

function fetchProductDetailsGDL(productObj) {
	var tmpProductObj ={};

	tmpProductObj.audienceType = productObj.AudienceType;
	tmpProductObj.productLineCode = productObj.ProductLineCode;
	tmpProductObj.productNumber = productObj.ProductNumber;
	tmpProductObj.seriesName = productObj.FullSerialNumber;  // this field name says number but its actually giving name
	tmpProductObj.productSeriesOID = productObj.ProductSeriesOID;
	tmpProductObj.serialNumber = productObj.SerialNumber;

	return tmpProductObj;
}

function fetchAllDevices(profileType){
	$.ajax({
		type: "GET",
		cache: false,
		url: "/hp-pps-services/hpsa/getAllDevices?cc="+getCCLC("cc")+"&lc="+getCCLC("lc"),
		contentType: "application/json",
		dataType: "json"
	}).done(function (data) {
		globalDeviceObject = data;
		var reqArrayForWCMContent = [];
		var products = [];
		var errorCodePresent = false;
		var statusCode;
		errorCodePresent = (data.ErrorItem!= undefined)? true : false;

		//If error codes are present
		if(errorCodePresent){
			statusCode = data.ErrorItem.statusCode;
			if(statusCode == 'SESSION_TIMEOUT'){
				//Send them to the session timed out view of dashboard
				if($("#pageIdentifier").val() == "Dashboard"){
					paintSessionTimedOutView();
				}
				else if(($("#pageIdentifier").val() == "Add Device") || ($("#pageIdentifier").val() == "Support Home")) {
					window.location.href = "/"+getCCLC("cc")+"-"+getCCLC("lc")+"/dashboard";
				}
			}
			else if(statusCode == 'SERVICE_ERROR'){
				if($("#pageIdentifier").val() == "Support Home"){
					//Trigger the error event
					$(document).trigger("serviceError");
				}
				//Send them to the error page
				if($("#pageIdentifier").val() == "Dashboard" || $("#pageIdentifier").val() == "Add Device"){
					window.location.href = "/" + getCCLC('cc') + '-' + getCCLC('lc') + '/error/500?source=fetchDevicesServiceError';		//appending the source for ALM 2866 500 error analysis
				}
			}
		}
		else{ // no error codes
			globalDataLayer.Dashboard.setValue("NoOfDevices", data.DeviceList.length);

			//sort to keep preferred devices first
	data.DeviceList.sort(function(x, y) {
        // true values first
        return (x.DeviceProperty.Preferred === y.DeviceProperty.Preferred)? 0 : x.DeviceProperty.Preferred? -1 : 1;
    });

			for(var i = 0; i < data.DeviceList.length; i++){
				//passing product object to fetchProductDetailsGDL to add details in Global Data Layer A&R
				products.push(fetchProductDetailsGDL(data.DeviceList[i].DeviceProperty));
			}
			
			// 7358: Anr for all pages
			for(var i = 0; i < data.DeviceList.length; i++){
				var tempObj = {};
				tempObj.seoProductName = data.DeviceList[i].DeviceProperty.seo_friendly_name;
				tempObj.seriesId = data.DeviceList[i].DeviceProperty.ProductSeriesOID;
				tempObj.modelId = data.DeviceList[i].DeviceProperty.ProductNameOID;
				tempObj.sku = data.DeviceList[i].DeviceProperty.ProductNumber;
				tempObj.productLine = data.DeviceList[i].DeviceProperty.ProductLineCode;
				tempObj.serialNumber = data.DeviceList[i].DeviceProperty.SerialNumber;
				reqArrayForWCMContent.push(tempObj);
			}
			
			//settings all products in Global Data Layer
			globalDataLayer.Dashboard.setValue("Products", products);
			if($("#pageIdentifier").val() == "Dashboard"){
				
				paintDeviceView(data);

			
			globalDataLayer.setValue("Template", "Dashboard");

				//Call to fetch WCM Data for products
				if(data.DeviceList.length > 0 && reqArrayForWCMContent.length > 0){
					for(var l=0; l < data.DeviceList.length; l++){
						personalDevicePNSNArr[l] = data.DeviceList[l].DeviceProperty.ProductNumber+data.DeviceList[l].DeviceProperty.SerialNumber;
					}
					fetchDeviceWCMData(reqArrayForWCMContent);
				}
			}
			$(document).trigger("devicesFetched");  //Custom Event trigger that is being listend to, in getWCMTabsAjax.js only when globalDeviceObject is empty/undefined
		}

		// if($("#pageIdentifier").val() == "Support Home"){
			// if($(".myDevicesDesktopContent").length > 0 ){
			// 	//&& $(".myDevicesDesktopContent").html() == ""
			// 	paintDeviceViewHome(data, profileType);
			// }
			// else{

			// }

		// }
		if($("#pageIdentifier").val() == "SWDSelfService" || $("#pageIdentifier").val() == "Product Home" || $("#pageIdentifier").val() == "Contact HP - Anonymous"){
			paintDeviceViewLandingPages(data);
		}
	}).fail(function (jqXHR, textStatus) {
		console.log('### fetch Devices failed ###');
		// $loginModal.modal('hide');
	});
}

function fetchDeviceWCMData(reqArr){
	$.ajax({
		type: "POST",
		url: "/hp-pps-services/webcontent/getDashboardProductTileIcons/cc/"+getCCLC("cc")+"/lc/"+getCCLC("lc"),
		contentType: "application/json",
		data: JSON.stringify(reqArr),
		dataType: "json"
	}).done(function (data) {
		for(var entry in data){
			var cardPosition = personalDevicePNSNArr.indexOf(entry);
			var paintingObj = {};
			paintingObj["cardPosition"] = cardPosition;
			paintingObj["contentArr"] = data[entry];
			var source = $("#deviceSpecificWCMContentTemplate").html();
		    var template = Handlebars.compile(source);
		    // $('.relatedWcmContent-'+entry).html(template(data[entry]));
		    $('.relatedWcmContent-'+entry).html(template(paintingObj));
		}
	}).fail(function (jqXHR, textStatus) {
		console.log('### fetch WCM Data for Devices failed ###');
		// $loginModal.modal('hide');
	});
}

function getClientDate(dateFormat){
	//dateFormat passed in parameters should be a string

	var dateToday = new Date();
	switch(dateFormat){
		case "mm-dd-yyyy" : {
			var formattedDate;
			if(dateToday.getMonth() < 9){
				formattedDate = "0"+(dateToday.getMonth() + 1);
			}
			else{
				formattedDate = dateToday.getMonth() + 1;
			}

			if(dateToday.getDate() < 10){
				formattedDateToday = "0"+(dateToday.getDate());
			}
			else{
				formattedDateToday = dateToday.getDate();
			}

			formattedDate = formattedDate +"-"+formattedDateToday+"-"+dateToday.getFullYear();
			return formattedDate;
		};
		break;
		case "mm/dd/yyyy" : {
			var formattedDate;
			if(dateToday.getMonth() < 9){
				formattedDate = "0"+(dateToday.getMonth() + 1);
			}
			else{
				formattedDate = dateToday.getMonth() + 1;
			}

			if(dateToday.getDate() < 10){
				formattedDateToday = "0"+(dateToday.getDate());
			}
			else{
				formattedDateToday = dateToday.getDate();
			}

			formattedDate = formattedDate +"/"+formattedDateToday+"/"+dateToday.getFullYear();
			return formattedDate;
		};
		break;
		case "dd-mm-yyyy" : {
			var formattedDate;
			if(dateToday.getDate() < 10){
				formattedDateToday = "0"+(dateToday.getDate());
			}
			else{
				formattedDateToday = dateToday.getDate();
			}
			formattedDate = formattedDateToday+"-";
			if(dateToday.getMonth() < 9){
				formattedDate = formattedDate+"0"+(dateToday.getMonth() + 1);
			}
			else{
				formattedDate = formattedDate+(dateToday.getMonth() + 1);
			}
			formattedDate = formattedDate+"-"+dateToday.getFullYear();
			return formattedDate;
		};
		break;
		case "dd/mm/yyyy" : {
			var formattedDate;
			if(dateToday.getDate() < 10){
				formattedDateToday = "0"+(dateToday.getDate());
			}
			else{
				formattedDateToday = dateToday.getDate();
			}
			formattedDate = formattedDateToday+"/";
			if(dateToday.getMonth() < 9){
				formattedDate = formattedDate+"0"+(dateToday.getMonth() + 1);
			}
			else{
				formattedDate = formattedDate+(dateToday.getMonth() + 1);
			}
			formattedDate = formattedDate+"/"+dateToday.getFullYear();
			return formattedDate;
		};
		break;
		case "yyyy-mm-dd" : {
			var formattedDate;
			formattedDate = dateToday.getFullYear()+"-";
			if(dateToday.getMonth() < 9){
				formattedDate = formattedDate+"0"+(dateToday.getMonth() + 1);
			}
			else{
				formattedDate = formattedDate+(dateToday.getMonth() + 1);
			}

			if(dateToday.getDate() < 10){
				formattedDateToday = "0"+(dateToday.getDate());
			}
			else{
				formattedDateToday = dateToday.getDate();
			}

			formattedDate = formattedDate+"-"+formattedDateToday;
			return formattedDate;
		};
		break;
		case "yyyy/mm/dd" : {
			var formattedDate;
			formattedDate = dateToday.getFullYear()+"/";
			if(dateToday.getMonth() < 9){
				formattedDate = formattedDate+"0"+(dateToday.getMonth() + 1);
			}
			else{
				formattedDate = formattedDate+(dateToday.getMonth() + 1);
			}

			if(dateToday.getDate() < 10){
				formattedDateToday = "0"+(dateToday.getDate());
			}
			else{
				formattedDateToday = dateToday.getDate();
			}

			formattedDate = formattedDate+"/"+formattedDateToday;
			return formattedDate;
		};
		break;
		case "yyyy-dd-mm" : {
			var formattedDate;
			formattedDate = dateToday.getFullYear()+"-";

			if(dateToday.getDate() < 10){
				formattedDateToday = "0"+(dateToday.getDate());
			}
			else{
				formattedDateToday = dateToday.getDate();
			}

			formattedDate = formattedDate+formattedDateToday+"-";
			if(dateToday.getMonth() < 9){
				formattedDate = formattedDate+"0"+(dateToday.getMonth() + 1);
			}
			else{
				formattedDate = formattedDate+(dateToday.getMonth() + 1);
			}
			return formattedDate;
		};
		break;
		case "yyyy/dd/mm" : {
			var formattedDate;
			formattedDate = dateToday.getFullYear()+"/";

			if(dateToday.getDate() < 10){
				formattedDateToday = "0"+(dateToday.getDate());
			}
			else{
				formattedDateToday = dateToday.getDate();
			}

			formattedDate = formattedDate+formattedDateToday+"/";
			if(dateToday.getMonth() < 9){
				formattedDate = formattedDate+"0"+(dateToday.getMonth() + 1);
			}
			else{
				formattedDate = formattedDate+(dateToday.getMonth() + 1);
			}
			return formattedDate;
		};
		break;
		case "mmm dd, yyyy":{
			var monthArr = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
			var dd = dateToday.getDate();
			if(dd < 10){
				dd = "0"+dd;
			}
			var mmm = monthArr[dateToday.getMonth()];
			var yyyy = dateToday.getFullYear();

			var formattedDate = mmm+" "+dd+", "+yyyy;
			return formattedDate;
		}
		break;
		default: {
			return dateToday; //Example Tue Sep 12 2017 14:10:03 GMT+0530 (IST)
		}
	}
}

function checkAndAddDevice(addBtnRef){
	var serialNo = $(addBtnRef).data("sno");
	var prodNo = $(addBtnRef).data("prodno");
	var warrantyDate = $(addBtnRef).data("warrantydate");
	// if(!isProductAdded(serialNo)){
		var reqPayload = {};
		reqPayload.serialNumber = serialNo;
		reqPayload.productNumber = prodNo;
		reqPayload.warrantyDate = warrantyDate;
		addDevice(reqPayload, addDeviceSuccess, addDeviceFail)
	// }
}

//Checks if product is already added compares data with globalDevice Object
function isProductAdded(serialNo){
	var deviceFound = false;
	if(!$.isEmptyObject(globalDeviceObject)){
		for(var entry in globalDeviceObject.DeviceList){
			if(globalDeviceObject.DeviceList[entry].DeviceProperty.SerialNumber == serialNo.toUpperCase()){
				deviceFound = true;	//Serial number present
				break;
			}
		}
		if(!deviceFound){
			return false;
		}
		else{
			return true;
		}
	}
}


function addDeviceInfoPostRegistration(){
	var serialNumber = localStorage.serialNumber;
	var productNumber = localStorage.productNumber;
	var productToBeAddedFlag = localStorage.productToBeAddedFlag;
	
	var requestJSON = {};
	requestJSON.serialNumber = serialNumber;
	requestJSON.productNumber = productNumber;
	requestJSON.purchaseDate = 	"1980-01-01";
	console.log("addDeviceInfoPostRegistration -> "+productToBeAddedFlag);
	addDevice(requestJSON, addDeviceSuccessPostRegistration, addDeviceFailPostRegistration);
}


//Add Device success call scenario
function addDeviceSuccessPostRegistration(){
	console.log("Error in add device call post registration");
	clearLocalStoragePostRegistration();
}

//Add Device failure call scenario
function addDeviceFailPostRegistration(){
	console.log("Error in add device call post registration");
	clearLocalStoragePostRegistration();
}

function clearLocalStoragePostRegistration(){
	localStorage.removeItem("serialNumber");
	localStorage.removeItem("productNumber");
	localStorage.removeItem("productToBeAddedFlag");
	fetchAllDevices(profileDetails.profileType);
}

function addDevice(addDeviceReqPayload, customSuccessCallback, customFailCallback){
	//addDeviceReqPayload - Object having 2 keys and their values - serialNumber & productNumber
	//customSuccessCallback - pass the function name you want to call on add device success
	//customFailCallback - pass the function name you want to call on add device fail
	
	//adding the ssid logic as part of CS for 20.4
	 var secureTokenVal = $('#secureTokenField').val(); //retrieve string in which key is stored
	 var ssidValue = "";
	 var tokenId = "hpsasid";	// hardcoding the token as we cannot have 2 token values for the same button
	 if(secureTokenVal.indexOf(tokenId)!=-1){  //check if the token key is present in the string of tokens
			ssidValue = JSON.parse($("#secureFieldJson").val());		
	 }
	var requestJSON = {};
	requestJSON.serialNumber = addDeviceReqPayload.serialNumber;
	requestJSON.productNumber = addDeviceReqPayload.productNumber;
	requestJSON.purchaseDate = addDeviceReqPayload.warrantyDate;
	requestJSON.entitlementLastCheck = getClientDate("yyyy-mm-dd");
	requestJSON.cc = getCCLC("cc");
	requestJSON.lc = getCCLC("lc");
	$.ajax({
		type: "POST",
		url: "/hp-pps-services/hpsa/addDevice?ssid="+ssidValue[tokenId],
		data : JSON.stringify(requestJSON),
		dataType: "json",
		beforeSend: function(xhr) {            
            xhr.setRequestHeader('Content-Type', 'application/json');
        }
	}).done(function (data) {
			populateSSID();
			var errorCodePresent = false;
			var statusCode;
			errorCodePresent = (data.ErrorItem!= undefined)? true : false;
			//If error codes are present
			if(errorCodePresent){
				statusCode = data.ErrorItem.statusCode;
				if(statusCode == 'SESSION_TIMEOUT'){
					//Send them to the session timed out view of dashboard
					if($("#pageIdentifier").val() == "Dashboard"){
						paintSessionTimedOutView();
					}
					else{
						window.location.href = "/"+getCCLC("cc")+"-"+getCCLC("lc")+"/dashboard";
					}
				}
				else if(statusCode == 'SERVICE_ERROR'){
					console.log("Error in add device call");
					 var errorData = {
						"requestUrl" : "/hp-pps-services/hpsa/addDevice?ssid="+ssidValue[tokenId],
						"data" : JSON.stringify(requestJSON),
						"errorReason" : "status code is service error"
					};
					var sourceVar = 'addDeviceServiceError';
					localStorage.setItem(sourceVar,JSON.stringify(errorData));
					window.location.href ="/" + getCCLC('cc') + '-' + getCCLC('lc') + '/error/500?source='+sourceVar;		//appending the source for ALM 2866 500 error analysis
				}
			}
			else{
				if(typeof(addDeviceReqPayload.dmdAddition) != "undefined"){
					customSuccessCallback(addDeviceReqPayload.serialNumber);
				}
				else if(addDeviceReqPayload.page = "eas"){					
					customSuccessCallback(addDeviceReqPayload.serialNumber, addDeviceReqPayload.productNumber);
				}
				else{
					customSuccessCallback();
				}
			}
	}).fail(function (jqXHR, textStatus) {
		populateSSID();
		if(typeof(addDeviceReqPayload.dmdAddition) != "undefined"){
			customFailCallback(addDeviceReqPayload.serialNumber);
		}
		else if(addDeviceReqPayload.page = "eas"){
			customSuccessCallback(addDeviceReqPayload.serialNumber, addDeviceReqPayload.productNumber);
		}
		else{
			localStorage.addDeviceFailed = {		//creating JSON object for error 500 analysis ALM# 2866
				"requestUrl" : "/hp-pps-services/hpsa/addDevice?ssid="+ssidValue[tokenId],
				"data" : JSON.stringify(requestJSON),
				"errorReason" : jqXHR.responseText
			}
			customFailCallback();
		}
	});
}
}catch(e){console.log("Module 'hpStyleR2': ",e);}
try{(function(){
if(!i$.isIE){
i$.addOnLoad(function(){
var _1=document.createElement("div");
var _2=ibmCfg.themeConfig.themeWebAppBaseURI;
_1.style.cssText="border:1px solid;border-color:red green;position:absolute;height:5px;top:-999px;background-image:url(\""+_2+"/icons/blank.gif\");";
document.body.appendChild(_1);
var _3=null;
try{
_3=document.defaultView.getComputedStyle(_1,"");
}
catch(e){
_3=_1.currentStyle;
}
var _4=_3.backgroundImage;
if((_3.borderTopColor==_3.borderRightColor)||(_4!=null&&(_4=="none"||_4=="url(invalid-url:)"))){
document.getElementsByTagName("body")[0].className+=" wpthemeImagesOff";
}
document.body.removeChild(_1);
});
}
})();


}catch(e){console.log("Module 'wp_theme_high_contrast': ",e);}