dojo.provide("atg.blueprint.facet");
dojo.require("dojo.cookie");
dojo.require("AccordionNav");


/*
    Ajax request for product list and pagination
*/
var lastHash='';
var lastParams='';
var currentHash='';
var initialContent = new Array();
var currentContent = new Array();
var sortOption='';
var searchSortOption='';
var viewNext='';
var viewAll='';
var highorlow='';
var totPage='15';
var selectedHowMany='';
var forSortBy='';
var searchParams='';
var splitParams= new Array();
var start,end,time;

var content = {
		start:'',
		selectedSortBy:'',
		addFacet:'',
		facetPageNum:'',
		currentPageNum:'',
		trail:'',
		trailSize:'',
		categoryId:'',
		advancedSearch:'',
		highorlow:'',
		selectedHowMany:'',
		viewAll:'',
		viewPreviousLink:'',
		viewNextLink:'',
		facetTrail:'',
		totPage:'15'
};
/*
var qs = window.location.search.substring(1); 
var vars = qs.split("&"); 
*/

function startsWith(str, prefix) {
    return str.indexOf(prefix) === 0;
}

function pollHash(){
	if(lastHash != window.location.hash){
		if(window.location.hash != '#richCartTrigger'){
			if((window.location.hash).split('=')[0] != '#clickActionData'){
				lastHash = window.location.hash;
				splitHash = lastHash.split('&');
				pageNum = splitHash[0].split('#')[1];
				
					
					for(var i=0; i<splitHash.length; i++){
						if(splitHash[i].split('=')[0]=='viewAll'){
							viewAll = splitHash[i].split('=')[1];
							break;
						} else {
							viewAll = '';
						}
					}
					
					for(var i=0; i<splitHash.length; i++){
						if(splitHash[i].split('=')[0]=='viewAll'){
							viewNext = splitHash[i].split('=')[1];
							break;
						} else {
							viewNext = '';
						}
					}
	
					for(var i=0; i<splitHash.length; i++){
						if(splitHash[i].split('=')[0]=='sort'){
							sortOption = splitHash[i].split('=')[1];
							break;
						} else {
							sortOption = '';
						}
					}
					
					for(var i=0; i<splitHash.length; i++){
						if(splitHash[i].split('=')[0]=='selectedHowMany'){
							selectedHowMany = splitHash[i].split('=')[1];
							break;
						} else {
							selectedHowMany = '';
						}
					}
		
					for(var i=0; i<splitHash.length; i++){
						if(splitHash[i].split('=')[0]=='highorlow'){
							highorlow = splitHash[i].split('=')[1];
							break;
						} else {
							highorlow = '';
						}
					}
	
					for(var i=0; i<splitHash.length; i++){
						if(splitHash[i].split('=')[0]=='currentPageNum'){
							currentPageNum = splitHash[i].split('=')[1];
							break;
						} else {
							currentPageNum = '';
						}
					}
					
					for(var i=0; i<splitHash.length; i++){
						if(splitHash[i].split('=')[0]=='totPage'){
							totPage = splitHash[i].split('=')[1];
							break;
						} else {
							totPage = '';
						}
					}
					
					//search filter params
					for(var i=0; i<splitHash.length; i++){
						if(splitHash[i].split('=')[0]=='clickActionData'){
							searchParams = splitHash[i].split('=')[1] + splitHash[i].split('=')[2];
							for(var j=0; j<searchParams.split('|').length; j++){
								splitParams[j] = searchParams.split('|')[j];
							}
							break;
						} 
					}
				
				//if(searchParams !='' && searchParams != lastParams){
					//lastParams = searchParams;
					
				if(searchParams !=''){
					//facetClickAction(splitParams[0],splitParams[1],splitParams[2],splitParams[3],splitParams[4],splitParams[5],splitParams[6],splitParams[7],splitParams[8],splitParams[9], false);
				}
				else {
					var startVal;
					if(pageNum == undefined || pageNum == ''){
						pageNum = 1;
						startVal = 1;
					} else if(startsWith(pageNum,'View') ==  true){
						startVal='';
					} else if(totPage == '' || totPage == 15){
						startVal = ((pageNum-1)*15)+1;
					} else if(totPage == 30){
						startVal = ((pageNum-1)*30)+1;
					} else if(totPage == 60){
						startVal = ((pageNum-1)*60)+1;
					} else if(totPage == 90){
						startVal = ((pageNum-1)*90)+1;
					} else {
						startVal = ((pageNum-1)*120)+1;
					}
		
                    var catId = splitHash[3];
                    if (catId == 'empty') {
                    	catId = '';
		            }
		            if(forSortBy == true){
		              	forSortBy = false;
		               	atg.blueprint.facet.loadDataPaginationForSortBy('1',sortOption,'',currentPageNum,splitHash[1],splitHash[2],catId,searchSortOption,highorlow,selectedHowMany,viewAll,splitHash[4],'',totPage);
		            } else if(viewAll != ''){
						atg.blueprint.facet.loadDataPagination(startVal,sortOption,'','',splitHash[1],splitHash[2],catId,searchSortOption,'',selectedHowMany,viewAll,splitHash[4],viewNext,pageNum,totPage);
					} else if(viewNext != ''){
						atg.blueprint.facet.loadDataPagination(startVal,sortOption,'','',splitHash[1],splitHash[2],catId,searchSortOption,'','','',splitHash[4],viewNext,pageNum,totPage);
					} else if(pageNum==1 && sortOption != ''){
						atg.blueprint.facet.loadDataPagination(startVal,sortOption,'','',splitHash[1],splitHash[2],catId,searchSortOption,'','','',splitHash[4],'',pageNum,totPage);
					} else if(pageNum==1 && selectedHowMany != ''){
						atg.blueprint.facet.loadDataPagination(startVal,sortOption,'','',splitHash[1],splitHash[2],catId,searchSortOption,'',selectedHowMany,'true',splitHash[4],'true',pageNum,totPage);
					} else if(pageNum==1){
						atg.blueprint.facet.loadDataPagination('',sortOption,dojo.cookie('addFacet'),'',dojo.cookie('trail'),dojo.cookie('trailSize'),dojo.cookie('categoryId'),searchSortOption,'','','','','','',totPage);
					} else if(sortOption != ''){
						atg.blueprint.facet.loadDataPagination(startVal,sortOption,'','',splitHash[1],splitHash[2],catId,searchSortOption,'','','',splitHash[4],'',pageNum,totPage);
					} else {
						atg.blueprint.facet.loadDataPagination(startVal,sortOption,'','',splitHash[1],splitHash[2],catId,searchSortOption,'','','',splitHash[4],'',pageNum,totPage);
					}
				}
			}
		} else {
			currentHash = lastHash;
			if(currentContent.length < 1){
				currentContent = initialContent;
			}
			setInterval(function(){
				lastHash = window.location.hash;
				},3000);
		}	
	}
}
setInterval(pollHash, 100);

atg.blueprint.facet={
    /*
		AJAX request content for target element
		parameter:
		   content: encapsulation data for ajax request,involved url ,and so on
		   target: target element object,such as div object
	*/
		
	loadNewPage:function(href) {
		var url = href;
		//window.alert('Event listener functional');
		//this.loadDataPagination();
	},
	
    loadData:function(content,target){
		if(content.addFacet != ''){
			dojo.cookie('addFacet',content.addFacet,{
				path:'/'
			});
			dojo.cookie('categoryId',content.categoryId,{
				path:'/'
			});
			dojo.cookie('trail',content.trail,{
				path:'/'
			});
			dojo.cookie('trailSize',content.trailSize,{
				path:'/'
			});
		} else {
			currentContent = content;
		}
 		if (!content.totPage || content.totPage == '') {
			var cookie = dojo.cookie('totPage');
 			if (cookie != undefined && cookie != null) {
				content.totPage = cookie;
			}
		} else {
			dojo.cookie('totPage',content.totPage,{
				path:'/'
			});						
		}

	    var _this=this;
	    if(!content.isAjax){
			content.isAjax = true;
		}
	    
//		if(content.advancedSearch && content.categoryId != ''){
//		   dojo.byId("facetCategory").style.marginTop="-30px";
//		}
		
	//	alert("content=" + content.trail+"===" + "addFacet="+ content.addFacet )
		/*var trail = content.trail;
		if(trail.match(content.addFacet)!=null){
			content.addFacet="";
			content.removeAllFacets="false";
		}*/
		if(content.facetPageNum == 1 && !content.start){
			content.facetPageNum = 0;
			content.start = 1;
		}
	    
		if(!content.url){
		    var facetContent = content.addFacet;
		    if(content.categoryId != '' && facetContent.indexOf('SRCH') == 0){		              
			    content.addFacet="";
			}
			content.url=contextPath+"/facet/facetGlossary.jsp";		
		}
		if(content.addFacet != ''&& content.addFacet.indexOf('SRCH') == 0)
		   content.trail = content.addFacet;
		var bindParam={
			url:content.url,
			content:content,
			load:function(data){
				_this.handleResponse(data,target);
			},
			error:function(err){
			//alert(err);
			}
		}
		
		dojo.xhrGet(bindParam);
	},
	
    /*
		ajax request content for pagination element
		parameter:
		   pStartValue: element start position
		   pSelectedSortBy: sort by property
		   pAddFacet: add facet
		   pCurrentPageNum: current page number
		   pTrail: trail
		   pTrailSize:t rail size
		   pCategoryId: being selected category
		   pHighorlow: highlight or not
		   pSelectedHowMany: render element number
		   pViewAll:whether view all element
	*/	 
	loadDataPagination:function(pStartValue,pSelectedSortBy,
								pAddFacet,pCurrentPageNum,
								pTrail,pTrailSize,pCategoryId,pAdvancedSearch,
								pHighorlow,pSelectedHowMany,pViewAll,pViewPreviousLink,pViewNextLink,pOMNIPageNum, pTotPage){
		var variableString;
		var paginationLinkText;
		if (pOMNIPageNum == '' || pOMNIPageNum == null) {
			paginationLinkText = (pStartValue/6);
			paginationLinkText = parseInt(paginationLinkText);
			paginationLinkText += 1;
		}
		else {
			paginationLinkText = pOMNIPageNum;
		}
		//alert(pTrail)
		var newTrail = pTrail;
				
		if(newTrail!=null && newTrail.match('"')!= null){
		
			pTrail= this.customReplaceTrail(newTrail, '"',"&quot;");
		}
		
		var facetPage = pOMNIPageNum - 1;
		if(pOMNIPageNum == ''){
			facetPage = 1;
		}
		
		if(isNaN(pOMNIPageNum)){
			pOMNIPageNum = 1;
			facetPage = 1;
		}

		content={
				start:pStartValue,
				selectedSortBy:pSelectedSortBy,
				addFacet:pAddFacet,
				facetPageNum:facetPage,
				currentPageNum:pCurrentPageNum,
				trail:pTrail,
				trailSize:pTrailSize,
				categoryId:pCategoryId,
				advancedSearch:pAdvancedSearch,
				highorlow:pHighorlow,
				selectedHowMany:pSelectedHowMany,
				viewAll:pViewAll,
				viewPreviousLink:pViewPreviousLink,
				viewNextLink:pViewNextLink,
				facetTrail:'',
				totPage:pTotPage
		};
		content.isAjax="true";
		
		/*	if(content.viewAll=='true')
		   {
		   var flashObj = dojo.query("#atg_b2cblueprint_contentWrapperCat")[0];
		   if(flashObj)
		        flashObj.style.display="none";
		   }		*/
		this.loadData(content);
		var s=s_gi(s_account);
		variableString=document.getElementById('OMNIPageNameVar').innerHTML;
		variableString+="|"+ 'Pagination' +"|"+ paginationLinkText;
		s.t();
		
	},
	 
	 /*
		ajax request content for sortBy element
		parameter:
		   pStartValue: element start position
		   pSelectedSortBy: sort by property
		   pAddFacet: add facet
		   pCurrentPageNum: current page number
		   pTrail: trail
		   pTrailSize:t rail size
		   pCategoryId: being selected category
		   pHighorlow: highlight or not
		   pSelectedHowMany: render element number
		   pViewAll:whether view all element
	*/	 
	loadDataPaginationForSortBy:function(pStartValue,pSelectedSortBy,
								pAddFacet,pCurrentPageNum,
								pTrail,pTrailSize,pCategoryId,pAdvancedSearch,
								pHighorlow,pSelectedHowMany,pViewAll,pViewPreviousLink,pViewNextLink, pTotPage){
								
		//Begin Omniture sort tracking
		var selectedSortOption;
		
		switch(pSelectedSortBy)
		{
			case 'relevance':
				selectedSortOption = 'Relevance';
				break;
			case 'bestSellerPriority':
				selectedSortOption = 'Best Sellers';
				break;
			case 'displayName':
				selectedSortOption = 'Item Name';
				break;
			case 'creationDate':
				selectedSortOption = 'New';
				break;
			case 'lowHighPrice':
				selectedSortOption = 'Price low to high';
				break;
			case 'highLowPrice':
				selectedSortOption = 'Price high to low';
				break;
		}
		
		content={
				start:pStartValue,
				selectedSortBy:pSelectedSortBy,
				addFacet:pAddFacet,
				currentPageNum:pCurrentPageNum,
				trail:pTrail,
				trailSize:pTrailSize,
				categoryId:pCategoryId,
                advancedSearch:pAdvancedSearch,
				highorlow:pHighorlow,
				selectedHowMany:pSelectedHowMany,
				viewAll:pViewAll,
				viewPreviousLink:pViewPreviousLink,
				viewNextLink:pViewNextLink,
				facetTrail:'',
				totPage:pTotPage
		};
		sortOption = pSelectedSortBy;
		content.isAjax="true";	
		this.loadData(content);
		
		var s=s_gi(s_account);
		var variableString;
		variableString=document.getElementById('OMNIPageNameVar').innerHTML;
		variableString+="|"+ "Sort" +"|"+ selectedSortOption;
		s.linkTrackVars='events,eVar30';
		s.linkTrackEvents='event11';
		s.events='event11';
		s.eVar30=selectedSortOption;
		
		s.tl(this,'o',variableString);
	},
     /*
		handle ajax response, put response data into target element.
		parameter:
		   data: response data
		   target:target element object,such as div object  #facetCategory
	*/
	
	handleResponse:function(data,target){
	    if(!target){
			var mainObject=dojo.query("#facetCategory")[0];
			
			if(mainObject){
                // append data to facetCategory
                mainObject.innerHTML=data;
				var flashObj = dojo.query("#atg_b2cblueprint_contentWrapperCat")[0];
				if(flashObj)
				   flashObj.style.display="block";

				// insert power reviews snippets
				var snippetIds = data.match(/pr-snippet-[\w\d]+/g);
				if(snippetIds) {
					for(var i = 0; i<snippetIds.length; i++) {
				        var productId = snippetIds[i].substr('pr-snippet-'.length);
	
				        if(typeof(snippet) != 'undefined') {
			                snippet(document, {pr_page_id: productId});
				        }
					}
				}
			} 
		}else{
			target.innerHTML=data;
		}
	},
	
	customReplaceTrail : function(str, replacingElem, finalReplaceVal){
		
		var newStr;
		//alert(str);
		while(str.match(replacingElem)!= null){
		     
			 var newStr = str.replace(replacingElem, finalReplaceVal);
			// alert(newStr);
			 str = newStr;
		}
//		alert("return" + str);
		return str;
	},
	
	changeHash:function(pStartValue,pSelectedSortBy,pAddFacet,pCurrentPageNum,pTrail,pTrailSize,pCategoryId,pAdvancedSearch,pHighorlow,pSelectedHowMany,pViewAll,pViewPreviousLink,pViewNextLink,pOMNIPageNum, pTotPage){
		var hash;
		if(!pOMNIPageNum){
			hash = '#';
		} else {
			hash = '#'+pOMNIPageNum
		}
		if(pTrail){
			hash = hash+'&'+pTrail;
		}
		if(pTrailSize){
			hash = hash+'&'+pTrailSize;
		}
		if(!pCategoryId || pCategoryId == ''){
                
			hash = hash+'&empty';
		} else {
			hash = hash+'&'+pCategoryId;
                }
		if(pViewPreviousLink){
			hash = hash+'&'+pViewPreviousLink;
		}
		if(pViewNextLink){
			hash = hash+'&'+'viewNext='+pViewNextLink;
			viewNext = pViewNextLink;
		}
		if(pViewAll){
			hash = hash+'&'+'viewAll='+pViewAll;
			viewAll = pViewAll;
		}
		if(pSelectedHowMany){
			hash = hash+'&'+'selectedHowMany='+pSelectedHowMany;
			selectedHowMany = pSelectedHowMany;
		}
		if(pSelectedSortBy){
			hash = hash+'&'+'sort='+pSelectedSortBy;
			sortOption = pSelectedSortBy;
		}
		if(pTotPage){
			hash = hash+'&'+'totPage='+pTotPage;
			totPage = pTotPage;
		}
		window.location.hash = hash;
		pollHash();
	},
	
	changeHashForSortBy:function(pStartValue,pSelectedSortBy,pAddFacet,pCurrentPageNum,pTrail,pTrailSize,pCategoryId,pAdvancedSearch,pHighorlow,pSelectedHowMany,pViewAll,pViewPreviousLink,pViewNextLink,pOMNIPageNum, pTotPage){
		var hash;
		if(!pOMNIPageNum){
			hash = '#';
		} else {
			hash = '#'+pOMNIPageNum
		}
		if(pTrail){
			hash = hash+'&'+pTrail;
		}
		if(pTrailSize){
			hash = hash+'&'+pTrailSize;
		}
		if(!pCategoryId || pCategoryId == ''){
                
			hash = hash+'&empty';
		} else {
			hash = hash+'&'+pCategoryId;
                }
		if(pViewPreviousLink){
			hash = hash+'&'+pViewPreviousLink;
		}
		if(pViewNextLink){
			hash = hash+'&'+'viewNext='+pViewNextLink;
			viewNext = pViewNextLink;
		}
		if(pViewAll){
			hash = hash+'&'+'viewAll='+pViewAll;
			viewAll = pViewAll;
		}
		if(pHighorlow){
			hash = hash+'&'+'highorlow='+pHighorlow;
			highorlow = pHighorlow;	
		}
		if(pCurrentPageNum){
			hash = hash+'&'+'currentPageNum='+pCurrentPageNum;
			currentPageNum = pCurrentPageNum;	
		}
		if(pSelectedHowMany){
			hash = hash+'&'+'selectedHowMany='+pSelectedHowMany;
			selectedHowMany = pSelectedHowMany;
		}
		if(pSelectedSortBy){
			hash = hash+'&'+'sort='+pSelectedSortBy;
			sortOption = pSelectedSortBy;
		}
		if(pTotPage){
			hash = hash+'&'+'totPage='+pTotPage;
			totPage = pTotPage;
		}
		forSortBy = true;
		window.location.hash = hash;
		pollHash();
		
	},
	
	clickActionData:function(data){
		var hash = '#';
		if(window.location.hash == '' || window.location.hash.split('=')[0] == '#clickActionData'){
			hash = '#'+'clickActionData='+data.cat + '|' + data.urlF+ '|' + data.urlP + '|' + data.action + '|' + data.tS + '|' + data.qty + '|' + data.addF + '|' + data.removeF + '|' + data.fValue + '|' + data.opid;
		} else {
			var newParams = 'clickActionData=' + data.cat + '|' + data.urlF+ '|' + data.urlP + '|' + data.action + '|' + data.tS + '|' + data.qty + '|' + data.addF + '|' + data.removeF + '|' + data.fValue + '|' + data.opid;
			var hashParams = window.location.hash.split('&');
			if(hashParams[hashParams.length-1].split('=')[0] != 'clickActionData'){
				hashParams[hashParams.length] = newParams;
			}else {
				hashParams[hashParams.length-1] = newParams;
			}
			for(var i=0; i < hashParams.length; i++){
				if(i == 0){
					hashParams[i] = hashParams[i].split('#')[1];
					hash = hash + hashParams[i];
				} else {
					hash = hash + '&' + hashParams[i]; 
				}
			}
		}
		window.location.hash = hash;
	}
}

