/** 
 * Initialisation function for global variables
 */
var postAction='';
var jsonDataReport;
var jsonDataExpert;
var jsonDataListing;
var jsonExpertListing;
var jsonDataListingIndex;
var urlFinder= {};
urlFinder['categories'] = [];
urlFinder['categoryname'] = [];
urlFinder['regionname'] = [];

//var domain_url = 'http://'+document.location.host+'/';
//var domain_url="http://50.57.125.207/info_frontend_dev/";
//var domain_url="http://localhost:8080/info_frontend/";
var domain_url="http://www.infollion.com/";
var site_url="http://www.infollion.com/";

var static_domain = '';
urlFinder['region'] = [];
//urlFinder['q'] = [];
urlFinder['price'] = [];
//urlFinder['specific'] = [];
urlFinder['releasedate'] = [];
//urlFinder['fq'] = [];
urlFinder['keyword']=[];
urlFinder['summary']=[];
var keyword_data= '';
var j='';
var urlassoc='';
var searchString = '';
/** Harded id conversion for prices */
var staticVarPrice = {};
staticVarPrice['200'] = '[* TO 200]';
staticVarPrice['201-500'] = '[200 TO 500]';
staticVarPrice['501-1000'] = '[501 TO 1000]';
staticVarPrice['1001-2000'] = '[1001 TO 2000]';
staticVarPrice['2001-'] = '[2001 TO *]';
/** Harded id conversion for prices */
var staticVarDate = {};
staticVarDate['30'] = '[NOW/DAY-30DAYS TO NOW/DAY%2B1DAY]';
staticVarDate['90'] = '[NOW/DAY-90DAYS TO NOW/DAY%2B1DAY]';
staticVarDate['180'] = '[NOW/DAY-180DAYS TO NOW/DAY%2B1DAY]';
staticVarDate['360'] = '[NOW/DAY-360DAYS TO NOW/DAY%2B1DAY]';
staticVarDate['1800'] = '[NOW/DAY-1800DAYS TO NOW/DAY%2B1DAY]';
staticVarDate['360-1-2'] = '[NOW/DAY-360DAYS TO NOW/DAY%2B1DAY]';
staticVarDate['1800-2-5'] = '[NOW/DAY-1800DAYS TO NOW/DAY%2B1DAY]';
staticVarDate['1800-5'] = '[NOW/DAY-1800DAYS TO NOW/DAY%2B1DAY]';
startDate = 'NOW/DAY-5DAYS';

/*( for searching and updating in the query)**/
var qSearch=0;
var stringKeyword = Array();

/* Written by Amit Gutpa - Post Action Calls */
function postActionCallback(){
    if(postAction=="cart"){
	window.location.href="http://"+document.location.host+"/cart";
    }
  
}


/**  Method to display the search listing */
function getSearchListing(search,cid, rid){
	//alert("search string"+searchString+" category ID");
	if(cid != null){
		searchString = '*:*';
		urlFinder['categories'].push(cid);
		cat = '&fq=categories:('+cid+')';
	}else{
	       if(rid != null){
		 searchString = '*:*';
		 urlFinder['region'].push(rid);
		 cat = '&fq=region:('+rid+')';
	       } else {
		cat = '';
		searchString = search;
	       }
	}
	
	document.getElementById("hiddenresultListing").innerHTML	= "";
	document.getElementById("ul_categoires").innerHTML			= "";
	document.getElementById("ul_regions").innerHTML				= "";
	document.getElementById("user_search_string").innerHTML		= "";	
	
	url = 'http://solr.infollion.com/core1/select/?q='+searchString+'&version=2.2&start=0&rows=400&indent=on&facet=true&wt=json&facet.mincount=1&facet.field=categories&facet.date.start='+startDate+'&facet.date.end=NOW/DAY%2B1DAY&facet.date.gap=%2B1DAY&facet.mincount=1&facet.field=region&json.wrf=?&facet.field=categoryname&facet.field=regionname'+cat;
//alert(url);	
	urlassoc = url;
	$('#hiddenresultListing').append('<div style="width:100%;margin-top:75px;" align="center"><img id="loading" src="'+site_url+'static/images/loading.gif" /></div>');
	
	$.getJSON(url, function(data){
			if(data){
				document.getElementById("hiddenresultListing").innerHTML = "";
				// do whatever require with returned data in json
				
				var jsonDataListing = data.response;
				
				
				//var jsonDataListing = jQuery.parseJSON(jsonSearch);
				var element = '';
				$.each(jsonDataListing, function(i,item){
					if(i == 'docs'){
						element += "<table cellpadding='1' cellspacing='0' width='100%' border='0' class='rtd' id='example'><thead><tr><th class='rw' align='left' width='62%' valign='middle'><strong>Title</strong></th><th class='rw' align='left' width='15%' valign='middle'><strong>Price</strong></th><th class='rw' align='left' width='23%' valign='middle'><strong>Release</strong></th></tr></thead><tbody>";
						$.each(item, function(j,itemInnerReport){
                                                    //alert(itemInnerReport.text);
						  var dstring = new Date(itemInnerReport.releasedate);
						  var strep = dstring.format("mmm,  yyyy");
						 
						  keyword_data = itemInnerReport.keyword+","+keyword_data;
						  
						  //Generate Link Here
						  itemTitle=itemInnerReport.text;
						  itemId=itemInnerReport.id;
						  itemTitle=itemTitle.replace(/\./g,"");
						  itemTitle=itemTitle.replace(/&/g,"");
						  itemTitle=itemTitle.replace(/-/,"");
						  itemTitle=itemTitle.replace(/:/g,"");
						  itemTitle=itemTitle.replace(/\(/g,"");
						  itemTitle=itemTitle.replace(/\)/g,"");
						  itemTitle=itemTitle.replace(/   /g," ");
						  itemTitle=itemTitle.replace(/  /g," ");
						  itemTitle=itemTitle.replace(/amp;/g,"");
						  itemTitle=itemTitle.replace(/ /g,"-");
						  itemTitle=itemTitle.replace(/--/g,"-");
						  
						  itemlink=site_url+"report_page/"+itemTitle+"-"+itemId+".html";
						  addreportbutton="";
						  if(gup("action")=="addreport"){
						  addreportbutton="<a class='addreportbutton' onClick=\"window.opener.addmoreHandle('"+itemId+"','"+itemInnerReport.text+"')\">Add Report</a>";
						  }
							element += "<tr class='rrc'><td align='left' width='60%' valign='middle' id='popup' class='cell'><a href='"+itemlink+"' >"+itemInnerReport.text+"<span><div class='popup_left_arrow'></div><br><div class='tl_head_01'>"+itemInnerReport.text+"</div><p><strong>Description</strong>: "+itemInnerReport.summary+"</p><div class='popup_bx_bott'><div class='popup_subbx_left'>Publisher: "+itemInnerReport.publisher+"<br>Product type: "+itemInnerReport.product_type+"<br>Pages: "+itemInnerReport.pages+"</div><div class='popup_subbx_right'>Price 	&#36; "+itemInnerReport.price+"<br><br><button type='submit' class='popup_button' id='"+itemInnerReport.id+"' title='go' onClick='addToCookie('"+'#'+itemInnerReport.id+"')'>Add to wishlist</button></div></div></span></a></td><td align='left' width='15%' valign='middle' class='span_rtd'>&nbsp;$"+itemInnerReport.price+"</td><td align='left' width='23%' valign='middle' class='span_rtd'>"+strep+addreportbutton+"</td></tr>";
													
						});
						element += "</tbody></table>";
						$('#hiddenresultListing').append(element);					
					}					
				});
				//alert(keyword_data);
				$("#keyword_filter").autocomplete(keyword_data.split(","));
				var jsonDataListing = data.facet_counts.facet_fields;
                                //alert(jsonDataListing.toSource());
				// Preparing the array of category and cateogry Id
				var temp = Array();
				var temp2 = Array();
                                var catCount = Array();
				$.each(jsonDataListing.categoryname, function(i,item){
					if(!((i+1) % 2 == 0)){
						temp.push(item);
					}
				});
				
				$.each(jsonDataListing.categories, function(i,item){
					if(!((i+1) % 2 == 0)){
						temp2.push(item);
					} else {
                                        catCount.push(item);
                                        }
				});
				// generating category listing now
				$.each(temp, function(k,itemInnerCategories){					
					element = "<li><a  id='categories_"+temp2[k]+"'  >"+itemInnerCategories+"("+catCount[k]+")</a></li>";					
					$('#ul_categoires').append(element);
				});
				
				// Preparing the array of region and regionID
				var temp = Array();
				var temp2 = Array();
                                var regionCount = Array();
				$.each(jsonDataListing.regionname, function(i,item){
					if(!((i+1) % 2 == 0)){
						temp.push(item);
					}
				});
				
				$.each(jsonDataListing.region, function(i,item){
					if(!((i+1) % 2 == 0)){
						temp2.push(item);
					} else {
                                         regionCount.push(item);
                                        }
				});
				// generating region listing now
				$.each(temp, function(k,itemInnerCategories){					
					element = "<li><a  id='region_"+temp2[k]+"'>"+itemInnerCategories+"("+regionCount[k]+")</a></li>";					
					$('#ul_regions').append(element);
				});		

						
					
				 $('#example').dataTable({"bPaginate": true,"bLengthChange": false, "bSort": false,"sPaginationType": "full_numbers"});
				// set events for the above created elements	
				setEvents();
				var tBox=$("#example_filter").children(); 
				  
				  tBox.keypress(function(evt){  var k = evt ? evt.which : window.event.keyCode; 
				  if(k==32) {
				    var tempArray =  tBox.val().split(" ");
				    
				    
				     
				      for(j=0;j<tempArray.length; j++){
					
				         stringKeyword.push(tempArray[j]);
				      }
					stringKeyword = removeDuplicateElement(stringKeyword);
				     
				      //alert(stringKeyword);
				      $("#keyword_data").html('');
				     for(i = 0; i<stringKeyword.length; i++){
				      
				       $("#keyword_data").append('<li><a id="summary_'+stringKeyword[i]+'">'+stringKeyword[i]+' </a></li>'); 
				       
				     }
				    setEvents();
				   // tBox.val() = '';
				    }
				    });
			}else{
				// check 
				alert("No data returned");
				return false;
			}
		});	
	
		
}
var text;var t;
/**
 * Method to display the listing of experts 
 */
function getExpertListing(param, cid, rid){
      if(cid != null){
		searchStringExpert = '*:*';
		urlFinder['categories'].push(cid);
		cat = '&fq=categories:('+cid+')';
	}else{
	       if(rid != null){
		 searchStringExpert = '*:*';
		 urlFinder['region'].push(rid);
		 cat = '&fq=region:('+rid+')';
	       } else {
		cat = '';
		searchStringExpert = param;
	       }
	}
	document.getElementById("hiddenresultListing_experts").innerHTML	= "";
	document.getElementById("ul_categoires_experts").innerHTML			= "";
	//document.getElementById("ul_regions").innerHTML				= "";
	//document.getElementById("user_search_string").innerHTML		= "";
       //alert(searchStringExpert);
       //alert(cat);
       url = 'http://solr.infollion.com/core0/select/?q='+searchStringExpert+'&version=2.2&start=0&rows=100&indent=on&wt=json&facet=true&facet.mincount=1&facet.field=categories&facet.field=categoryname&fq=role_name:EXPERT&json.wrf=?'+cat;
      // alert(url);
       urlassoc = url;
       $('#hiddenresultListing_experts').append('<div style="width:100%;margin-top:75px;" align="center"><img id="loading" src="'+site_url+'static/images/loading.gif" /></div>');
	//url = 'http://solr.infollion.com/core0/select/?q='+param+'&version=2.2&start=0&rows=10&indent=on&wt=json&json.wrf=?';
	$.getJSON(url, function(data){
	  
			if(data){
			  document.getElementById("hiddenresultListing_experts").innerHTML = "";
				jsonDataExpert = data.response;				
				var element = '';
				//alert(jsonDataExpert.numFound);
				addexpertbutton="";
				
				
				if(jsonDataExpert.numFound != 0){
				$.each(jsonDataExpert, function(i,item){
					if(i == 'docs'){
						$.each(item, function(j,itemInnerExperts){
						  //alert(itemInnerExperts.id);
						  if(gup('action')=="addexpert"){
						  text="Expert in "+itemInnerExperts.area_of_expertise;
						   
						  	/*
						    regX = "/\n/gi" ;

							t = new String(text);
							t = t.replace(regX," ");
							*/ 
							t=text.replace(/\r\n/g," ");

						  
						  	addexpertbutton="<a class='addexpertbutton' onClick=\"window.opener.addmoreHandle('"+itemInnerExperts.id+"','"+itemInnerExperts.code+"','"+t+"')\">Add Expert</a>";
						  	action="&action=addexpert";
				 		}
						  else{
						  	addexpertbutton="";
						  	action="";
						  }
						   
						  var photo_url=itemInnerExperts.photo_url;
						  photo_url=photo_url.replace(/ /g,"%20");
							element = "<div class='experts'><a href='"+domain_url+"industry-expert/expert-"+itemInnerExperts.code+action+"'><img border='0' alt='preview' width='68px'  src="+photo_url+"></a><p style='width:436px; float:right;'><strong><a href='"+domain_url+"industry-expert/expert-"+itemInnerExperts.code+action+"'>"+itemInnerExperts.code+"</a></strong><br><span class='span_text01'>Expert in "+itemInnerExperts.area_of_expertise+"</span>"+addexpertbutton+"</p><p class='span_text02'></p></div>";
							 			
												
							$('#hiddenresultListing_experts').append(element);
						});
					}					
				});
				 
				var jsonDataListing = data.facet_counts.facet_fields;
				//alert(data.facet_counts.facet_fields.toSource());
				// Preparing the array of category and cateogry Id
				var temp = Array();
				var temp2 = Array();
                                var catCount = Array();
				$.each(jsonDataListing.categoryname, function(i,item){
					if(!((i+1) % 2 == 0)){
						temp.push(item);
					}
				});
				
				$.each(jsonDataListing.categories, function(i,item){
					if(!((i+1) % 2 == 0)){
						temp2.push(item);
					} else {
                                        catCount.push(item);
                                        }
				});
				// generating category listing now
				$.each(temp, function(k,itemInnerCategories){
				   
					element = "<li><a  id='categories_"+temp2[k]+"'>"+itemInnerCategories+"("+catCount[k]+")</a></li>";					
					$('#ul_categoires_experts').append(element);
				});
				setExpertEvents();
	//initPaginationExperts();
				} else {
				  element = "<div class='experts'>No data returned</div>";
				  $('#hiddenresultListing_experts').append(element);
				  
				}

			} else {
			  alert("No data returned");
			  return false;
			}
	});
}

/*
 * method to display databases;
 */
 
function getDatabaseListing(param, cid, rid){
      if(cid != null){
		searchStringDatabase = '*:*';
		urlFinder['categories'].push(cid);
		cat = '&fq=categories:('+cid+')';
	}else{
	       if(rid != null){
		 searchStringDatabase = '*:*';
		 urlFinder['region'].push(rid);
		 cat = '&fq=region:('+rid+')';
	       } else {
		cat = '';
		searchStringDatabase = param;
	       }
	}
	document.getElementById("hiddenresultListing_experts").innerHTML	= "";
	document.getElementById("ul_categoires_experts").innerHTML			= "";
	//document.getElementById("ul_regions").innerHTML				= "";
	//document.getElementById("user_search_string").innerHTML		= "";
       //alert(searchStringDatabase);
       //alert(cat);
       url = 'http://solr.infollion.com/core1/select/?q='+searchStringDatabase+'&version=2.2&start=0&rows=10&indent=on&wt=json&json.wrf=?';
       //url = 'http://solr.infollion.com/core0/select/?q='+searchStringDatabase+'&version=2.2&start=0&rows=100&indent=on&wt=json&facet=true&facet.mincount=1&facet.field=categories&facet.field=categoryname&fq=role_name:EXPERT&json.wrf=?'+cat;
       //alert(url);
       urlassoc = url;
       $('#hiddenresultListing_experts').append('<div style="width:100%;margin-top:75px;" align="center"><img id="loading" src="'+site_url+'static/images/loading.gif" /></div>');
	//url = 'http://solr.neutronsoft.com:8080/solr/user/select/?q='+param+'&version=2.2&start=0&rows=10&indent=on&wt=json&json.wrf=?';
	$.getJSON(url, function(data){
	  //alert(data);
	  
			if(data){
			  document.getElementById("hiddenresultListing_experts").innerHTML = "";
				jsonDataDatabase = data.response;				
				var element = '';
				//alert(jsonDataDatabase.toSource());
				//alert(jsonDataDatabase.numFound);
				if(jsonDataDatabase.numFound != 0){
				$.each(jsonDataDatabase, function(i,item){
					if(i == 'docs'){
						$.each(item, function(j,itemInnerDatabase){
						  //alert(itemInnerDatabase.id);
							element = "<div class='experts'><a href='database_page?id="+itemInnerDatabase.id+"'></a><p style='width:436px; '><strong><a href='database_page?id="+itemInnerDatabase.id+"'>"+itemInnerDatabase.title+"</a></strong><br><span class='span_text01'>"+itemInnerDatabase.description+"</span></p><p class='span_text02'><i>"+itemInnerDatabase.parameters+"</i></p></div>";
							$('#hiddenresultListing_experts').append(element);
						});
					}					
				});
				setDatabaseEvents(); 
				var jsonDataListing = data.facet_counts.facet_fields;
				//alert(data.facet_counts.facet_fields.toSource());
				// Preparing the array of category and cateogry Id
				var temp = Array();
				var temp2 = Array();
                                var catCount = Array();
				
				
	//initPaginationExperts();
				} else {
				  element = "<div class='experts'>No data returned</div>";
				  $('#hiddenresultListing_experts').append(element);
				  
				}

			} else {
			  alert("No data returned");
			  return false;
			}
	});
}

/**  Method to set events for the filter links, function to  be called
 * on listing page.*/
function setEvents(){
	// events for categories 
	$( "#ul_categoires li a" ).click( function() {			
		if($(this).attr('class') == ''){			
			$(this).addClass("active");			
			element = "<li><a class='active'>"+$(this).context.innerHTML+"<img id='user_search_string_"+$(this).attr('id')+"' onClick='javascript:removeUserSearchString(this.id);' src='"+site_url+"static/images/close_button.gif' border='0' class='close_button' alt='' /></a></li>";
			$('#user_search_string').append(element);		
			var imgattr = "<img  style='float: right; margin: -14px 0px 0pt 0pt;' id='user_search_string_"+$(this).attr('id')+"_' onClick='javascript:removeUserSearchString2(this.id);' src='"+site_url+"static/images/close_button.gif' border='0' class='close_button' alt='' />";
			$(this).parent().append(imgattr);
			createUrl($(this).attr('id'),'categories');
		}		
	});
	// events for regions
	$( "#ul_regions li a" ).click( function() {			
		if($(this).attr('class') == ''){			
			$(this).addClass("active");			
			element = "<li><a class='active'>"+$(this).context.innerHTML+"<img id='user_search_string_"+$(this).attr('id')+"' onClick='javascript:removeUserSearchString(this.id);' src='"+site_url+"static/images/close_button.gif' border='0' class='close_button' alt='' /></a></li>";
			$('#user_search_string').append(element);		
			var imgattr = "<img  style='float: right; margin: -14px 0px 0pt 0pt;' id='user_search_string_"+$(this).attr('id')+"_' onClick='javascript:removeUserSearchString2(this.id);' src='"+site_url+"static/images/close_button.gif' border='0' class='close_button' alt='' />";
			$(this).parent().append(imgattr);
			createUrl($(this).attr('id'),'region');			
		}
	}); 
	
	// events for left section 
	$( "#left_filter_options a" ).click( function() {	
		if($(this).attr('class') == ''){			
			$(this).addClass("active");			
			element = "<li><a class='active'>"+$(this).context.innerHTML+"<img id='user_search_string_"+$(this).attr('id')+"' onClick='javascript:removeUserSearchString(this.id);' src='"+site_url+"static/images/close_button.gif' border='0' class='close_button' alt='' /></a></li>";
			$('#user_search_string').append(element);		
			var imgattr = "<img  style='float: right; margin: -14px 0px 0pt 0pt;' id='user_search_string_"+$(this).attr('id')+"_' onClick='javascript:removeUserSearchString2(this.id);' src='"+site_url+"static/images/close_button.gif' border='0' class='close_button' alt='' />";
			$(this).parent().append(imgattr);
			var category = $(this).attr('id').split("_");			
			createUrl($(this).attr('id'),category[0]);			
		}
	}); 
}

function setExpertEvents(){
  // events for categories 
  
	$( "#ul_categoires_experts li a" ).click( function() {			
		if($(this).attr('class') == ''){			
			$(this).addClass("active");			
			element = "<li><a class='active'>"+$(this).context.innerHTML+"<img id='user_search_string_"+$(this).attr('id')+"' onClick='javascript:removeUserExpertSearchString(this.id);' src='"+site_url+"static/images/close_button.gif' border='0' class='close_button' alt='' /></a></li>";
			$('#user_search_string').append(element);		
			var imgattr = "<img  style='float: right; margin: -14px 0px 0pt 0pt;' id='user_search_string_"+$(this).attr('id')+"_' onClick='javascript:removeUserExpertSearchString2(this.id);' src='"+site_url+"static/images/close_button.gif' border='0' class='close_button' alt='' />";
			$(this).parent().append(imgattr);
			createExpertUrl($(this).attr('id'),'categories');
		}		
	});
	$( "#left_filter_options a" ).click( function() {	
		if($(this).attr('class') == ''){			
			$(this).addClass("active");			
			element = "<li><a class='active'>"+$(this).context.innerHTML+"<img id='user_search_string_"+$(this).attr('id')+"' onClick='javascript:removeUserExpertSearchString(this.id);' src='"+site_url+"static/images/close_button.gif' border='0' class='close_button' alt='' /></a></li>";
			$('#user_search_string').append(element);		
			var imgattr = "<img  style='float: right; margin: -14px 0px 0pt 0pt;' id='user_search_string_"+$(this).attr('id')+"_' onClick='javascript:removeUserExpertSearchString2(this.id);' src='"+site_url+"static/images/close_button.gif' border='0' class='close_button' alt='' />";
			$(this).parent().append(imgattr);
			var category = $(this).attr('id').split("_");	
			//alert(category[0]);
			createExpertUrl($(this).attr('id'),category[0]);			
		}
	}); 
	
}

function setDatabaseEvents(){
  // events for categories 
  
	
	$( "#left_filter_options a" ).click( function() {	
		if($(this).attr('class') == ''){			
			$(this).addClass("active");			
			element = "<li><a class='active'>"+$(this).context.innerHTML+"<img id='user_search_string_"+$(this).attr('id')+"' onClick='javascript:removeUserDatabaseSearchString(this.id);' src='"+site_url+"static/images/close_button.gif' border='0' class='close_button' alt='' /></a></li>";
			$('#user_search_string').append(element);		
			var imgattr = "<img  style='float: right; margin: -14px 0px 0pt 0pt;' id='user_search_string_"+$(this).attr('id')+"_' onClick='javascript:removeUserDatabaseSearchString2(this.id);' src='"+site_url+"static/images/close_button.gif' border='0' class='close_button' alt='' />";
			$(this).parent().append(imgattr);
			var category = $(this).attr('id').split("_");	
			//alert(category[0]);
			createDatabaseUrl($(this).attr('id'),category[0]);			
		}
	}); 
	
}

function searchPagination(){
	// Listing pagination	
	var num_entries = $('#hiddenresultListing ul li').length; 
	// Create content inside pagination element
	$("#pg").pagination(num_entries, {
		callback: searchPageselectCallback3,
		items_per_page:1, // This needs to be changed in calbeack function also
		show_numbers:true
	});
}	
function searchPageselectCallback(page_index, jq){	
	var items_per_page = 4;
	//alert(page_index);
	urlIndex ="http://solr.infollion.com/core1/select/?q=*%3A*&version=2.2&start=0&rows=16&indent=on&facet=true&wt=json&facet.field=categories&facet.mincount=1&facet.field=categories&facet.date.start=NOW/DAY-5DAYS&facet.date.end=NOW/DAY%2B1DAY&facet.date.gap=%2B1DAY&facet.field=region&facet.field=region&json.wrf=?&facet.field=categoryname&facet.field=regionname&fq=keyword:featured"
	var newcontent = '';	
	$.getJSON(urlIndex, function(data){
			if(data){
				jsonDataListingIndex = data.response;
				//alert(jsonDataListingIndex.docs.length);
	
	
	var max_elem = Math.min((page_index+1) * items_per_page, jsonDataListingIndex.docs.length);
	
	// Iterate through a selection of the content and build an HTML string
	for(var i=page_index*items_per_page;i<max_elem;i++)
	{
	  
	        //var strep = jsonDataListing.docs[i].releasedate.split("T");
		 var dstring = new Date(jsonDataListingIndex.docs[i].releasedate);
		var strep = dstring.format("mmm, yyyy");
		
		var rtitle=jsonDataListingIndex.docs[i].text;
		var rid=jsonDataListingIndex.docs[i].id;
		
		//Generate Link Here
						  itemTitle=jsonDataListingIndex.docs[i].text;
						  itemId=jsonDataListingIndex.docs[i].id;
						  itemTitle=itemTitle.replace(/\./g,"");
						  itemTitle=itemTitle.replace(/&/g,"");
						  itemTitle=itemTitle.replace(/-/,"");
						  itemTitle=itemTitle.replace(/:/g,"");
						  itemTitle=itemTitle.replace(/\(/g,"");
						  itemTitle=itemTitle.replace(/\)/g,"");
						  itemTitle=itemTitle.replace(/   /g," ");
						  itemTitle=itemTitle.replace(/  /g," ");
						  itemTitle=itemTitle.replace(/amp;/g,"");
						  itemTitle=itemTitle.replace(/ /g,"-");
						  itemTitle=itemTitle.replace(/--/g,"-");
						  
						  itemlink=site_url+"report_page/"+itemTitle+"-"+itemId+".html";
		
		 
		
		newcontent += "<div class='reports'><p><strong><a href='"+itemlink+"'>"+jsonDataListingIndex.docs[i].text+"</a></strong><br/>"+jsonDataListingIndex.docs[i].summary.substr(0,70).replace(/<br>/ig,"")+"</p><div class='r_v_s'><a href='"+itemlink+"'>View Summary</a></div> <div class='r_d_s_bx'><span class='r_d_s'><a href='"+itemlink+"'>"+strep+"</a> &nbsp;| &nbsp; <a href='"+itemlink+"'>&#36; "+jsonDataListingIndex.docs[i].price+"</a></span></div> </div>";					
	}	
			$('#Searchresult').empty().append(newcontent);
		}
	});
	
	return false;
	
}
function searchPageselectCallback2(page_index,jq){
	// Experts
	var items_per_page = 4;
	
	var max_elem = Math.min((page_index+1) * items_per_page, jsonDataExpert.docs.length);
	var newcontent = '';
	
	// Iterate through a selection of the content and build an HTML string
	for(var i=page_index*items_per_page;i<max_elem;i++)
	{	var photo_url;
        	if(jsonDataExpert.docs[i].photo_url){
                    photo_url = jsonDataExpert.docs[i].photo_url;
                } else {
                    photo_url = 'upload/no-image.jpg';
                }
                
                //Strip white space
                photo_url=photo_url.replace(/ /g,"%20");
                
		newcontent += "<div class='experts'><a href='"+domain_url+"industry-expert/expert-"+jsonDataExpert.docs[i].code+"'><img width='47px' src="+photo_url+" border='0' class='no_img' alt='preview' /></a><p><strong><a href='"+domain_url+"industry-expert/expert-"+jsonDataExpert.docs[i].code+"'>"+jsonDataExpert.docs[i].code+"</a></strong><br />";
		var expertIn = (jsonDataExpert.docs[i].area_of_expertise)?" Expert in "+jsonDataExpert.docs[i].area_of_expertise:'';
		newcontent += "<span class='span_text01'>"+expertIn+"</span></p></div>";					
	}		
	$('#SearchresultExperts').empty().append(newcontent);
	return false;
}

function searchPageselectCallback3(page_index,jq){
		   // Listing		   
		   var items_per_page = 1;		   
		   var max_elem = Math.min((page_index+1) * items_per_page, jsonDataListing.report.length);
		   var newcontent = '';
		   // Iterate through a selection of the content and build an HTML string
		   newcontent += "<ul>";
										   
		   for(var i=page_index*items_per_page;i<max_elem;i++)
		   {
				   newcontent += "<li><div class='search_report_list_bg'><div class='sea_rep_title'><span class='sea_rep_list_link' ><a class='toolbox_glossary_roll_l_view' href='"+jsonDataListing.report[i].link+"' >"+jsonDataListing.report[i].text+"<span class='toolbox_l_view'><div class='toolbox_glossary_show_l_line'></div><div class='tl_head'>"+jsonDataListing.report[i].text+"</div><p><strong>English Name: </strong>"+jsonDataListing.report[i].english_name+"<strong>   Description: </strong>"+jsonDataListing.report[i].description+"</p><div class='tl_b'><div class='tl_b_left'>Publisher: "+jsonDataListing.report[i].publisher+"<br />Product Type: "+jsonDataListing.report[i].product_type+"<br />Pages: "+jsonDataListing.report[i].pages+"</div><div class='tl_b_right'>Price: $"+jsonDataListing.report[i].price+"<br /><br /><button type='submit' class='submit_button' title='go'>Add to wishlist</button></div></div></span></a></span></div><div class='sea_rep_price'>$"+jsonDataListing.report[i].price+"</div><div class='sea_rep_release'>"+jsonDataListing.report[i].releasedate+"</div></div></li>";                                
		   }        
		   newcontent += "</ul>";
		   $('#search_report_list').empty().append(newcontent);
		   return false;
   }
/** 
 * Initialisation function for pagination
 */
function initPaginationReports() {
	var num_entries = $('#hiddenresult div.reports').length;                
	// Create content inside pagination element
	$(".searchresult_pagination").pagination(num_entries, {
		callback: searchPageselectCallback,
		items_per_page:4 // This needs to be changed in calbeack function also
	});	
	
}	
/** 
 * Initialisation function for pagination
 */
function initPaginationExperts(){
	// Experts pagination	
	var num_entries = $('#hiddenresultExperts div.experts').length;                
	// Create content inside pagination element
	$(".searchresult_pagination_experts").pagination(num_entries, {
		callback: searchPageselectCallback2,
		items_per_page:4 // This needs to be changed in calbeack function also
	});
}
 
/** update and remove the user search string on listing page. */
function removeUserSearchString(id){	
	$('#'+id).parent().parent().remove();	
	$('#'+id.substr(19,id.length)).parent().children().last().remove();
	$('#'+id.substr(19,id.length)).removeClass('active');
	var categoryId = id.split("_");
	var len = categoryId.length;	
	if(categoryId[len-2] == 'price'){
		var requestUrl = deleteUri(categoryId[len-2],staticVarPrice[categoryId[len-1]]);
	}else if(categoryId[len-2] == 'releasedate'){
		var requestUrl = deleteUri(categoryId[len-2],staticVarDate[categoryId[len-1]]);
	}else{
		var requestUrl = deleteUri(categoryId[len-2],categoryId[len-1]);
	}
	
	
	
	  updateList(requestUrl);
}
function removeUserExpertSearchString(id){	
	$('#'+id).parent().parent().remove();	
	$('#'+id.substr(19,id.length)).parent().children().last().remove();
	$('#'+id.substr(19,id.length)).removeClass('active');
	var categoryId = id.split("_");
	var len = categoryId.length;	
	if(categoryId[len-2] == 'price'){
		var requestUrl = deleteUri(categoryId[len-2],staticVarPrice[categoryId[len-1]]);
	}else if(categoryId[len-2] == 'releasedate'){
		var requestUrl = deleteUri(categoryId[len-2],staticVarDate[categoryId[len-1]]);
	}else{
		var requestUrl = deleteUri(categoryId[len-2],categoryId[len-1]);
	}
	
	
	
	  updateExpertList(requestUrl);
}

function removeUserDatabaseSearchString(id){	
	$('#'+id).parent().parent().remove();	
	$('#'+id.substr(19,id.length)).parent().children().last().remove();
	$('#'+id.substr(19,id.length)).removeClass('active');
	var categoryId = id.split("_");
	var len = categoryId.length;	
	if(categoryId[len-2] == 'price'){
		var requestUrl = deleteUri(categoryId[len-2],staticVarPrice[categoryId[len-1]]);
	}else if(categoryId[len-2] == 'releasedate'){
		var requestUrl = deleteUri(categoryId[len-2],staticVarDate[categoryId[len-1]]);
	}else{
		var requestUrl = deleteUri(categoryId[len-2],categoryId[len-1]);
	}
	
	
	
	  updateDatabaseList(requestUrl);
}
/** Close button specific function ( jugad) */
function removeUserSearchString2(id){
	id = id.substr(0,id.length-1);
	$('#'+id).parent().parent().remove();
	$('#'+id.substr(0,id.length)+'_').remove();
	$('#'+id.substr(19,id.length)).removeClass('active');
	var categoryId = id.split("_");
	var len = categoryId.length;
	if(categoryId[len-2] == 'price'){
		var requestUrl = deleteUri(categoryId[len-2],staticVarPrice[categoryId[len-1]]);
	}else if(categoryId[len-2] == 'releasedate'){
		var requestUrl = deleteUri(categoryId[len-2],staticVarDate[categoryId[len-1]]);
	}else{
		var requestUrl = deleteUri(categoryId[len-2],categoryId[len-1]);		 
	}
	
	
	
	 updateList(requestUrl);
	
}

function removeUserExpertSearchString2(id){
	id = id.substr(0,id.length-1);
	$('#'+id).parent().parent().remove();
	$('#'+id.substr(0,id.length)+'_').remove();
	$('#'+id.substr(19,id.length)).removeClass('active');
	var categoryId = id.split("_");
	var len = categoryId.length;
	if(categoryId[len-2] == 'price'){
		var requestUrl = deleteUri(categoryId[len-2],staticVarPrice[categoryId[len-1]]);
	}else if(categoryId[len-2] == 'releasedate'){
		var requestUrl = deleteUri(categoryId[len-2],staticVarDate[categoryId[len-1]]);
	}else{
		var requestUrl = deleteUri(categoryId[len-2],categoryId[len-1]);		 
	}
	
	
	
	 updateExpertList(requestUrl);
	
}

function removeUserDatabaseSearchString2(id){
	id = id.substr(0,id.length-1);
	$('#'+id).parent().parent().remove();
	$('#'+id.substr(0,id.length)+'_').remove();
	$('#'+id.substr(19,id.length)).removeClass('active');
	var categoryId = id.split("_");
	var len = categoryId.length;
	if(categoryId[len-2] == 'price'){
		var requestUrl = deleteUri(categoryId[len-2],staticVarPrice[categoryId[len-1]]);
	}else if(categoryId[len-2] == 'releasedate'){
		var requestUrl = deleteUri(categoryId[len-2],staticVarDate[categoryId[len-1]]);
	}else{
		var requestUrl = deleteUri(categoryId[len-2],categoryId[len-1]);		 
	}
	
	
	
	 updateDatabaseList(requestUrl);
	
}
/** Url generation Helper functions */
/**---------------- Function to remove element by Key from an array ------------------*/
function removeByIndex(arr, index) {
    arr.splice(index, 1);
}

/**---------------- Function to remove element by Value from an array-----------------*/
function removeByValue(arrkey, val) {
    for(var i=0; i<urlFinder[arrkey].length; i++) {
        if(urlFinder[arrkey][i] == val) {
            urlFinder[arrkey].splice(i, 1);
            break;
        }
    }
}

/**---------------- Function implode and explode an array ----------------------------*/
/**---------------- Function for exploding array in script--------------------------- */
function explodeArray(item,delimiter) {
	tempArray=new Array(1);
	var Count=0;
	var tempString=new String(item);

	while (tempString.indexOf(delimiter)>0) {
	tempArray[Count]=tempString.substr(0,tempString.indexOf(delimiter));
	tempString=tempString.substr(tempString.indexOf(delimiter)+1,tempString.length-tempString.indexOf(delimiter)+1);
	Count=Count+1
	}

	tempArray[Count]=tempString;
	return tempArray;
}

/**------------- Function for implode an array in script ------------------------------*/

var myString = new String('red,green,blue');
var myArray = myString.split(','); 

/**------------------- end of implode and explode functions in script -----------------*/
/**------------------- funtion to modify the url --------------------------------------*/
function modifyUrl(){
	var url = '';
	var str = '';
	var flag = 0;
		for(key in urlFinder){
			str = '';			
			if(!urlFinder[key].length)
				continue;
			for(var x=0;x<urlFinder[key].length;x++){
				if(urlFinder[key].length>1){					
					str += urlFinder[key][x]+' OR ';					
					flag = 1;
				}else if(urlFinder[key].length==1){
					str += urlFinder[key][x];				
				}
			}
			if(flag){
				str = str.substr(0,str.length-4);
				flag = 0;
			}			
			str = '('+str+')';
			
			url += '&fq='+key+':'+str;
			
		}		
		return urlassoc+url;
}

/**------------------- function to create the new url ---------------------------------*/
function createUrl(catId,catName){
	catId = catId.split('_');
	if(catName == 'price'){
		urlFinder[catName].push(staticVarPrice[catId[1]]);
	}else if(catName == 'releasedate'){
		urlFinder[catName].push(staticVarDate[catId[1]]);
	}else{		
		urlFinder[catName].push(catId[1]);
		
	}
	//alert(modifyUrl);
	var requestUrl = modifyUrl();
	//alert(requestUrl);
	updateList(requestUrl);	
	//updateExpertList(requestUrl);
}

function createExpertUrl(catId,catName){
  catId = catId.split('_');
	if(catName == 'price'){
		urlFinder[catName].push(staticVarPrice[catId[1]]);
	}else if(catName == 'releasedate'){
		urlFinder[catName].push(staticVarDate[catId[1]]);
	}else{		
		urlFinder[catName].push(catId[1]);
		
	}
	//if(catName == 'keyword'){
	  //urlFinder[catName].push();
	//}
	//alert(urlFinder[catName]);
	//alert(modifyUrl);
	var requestUrl = modifyUrl();
	//alert(requestUrl);
	//updateList(requestUrl);	
	updateExpertList(requestUrl);
}

function createDatabaseUrl(catId,catName){
  catId = catId.split('_');
	if(catName == 'price'){
		urlFinder[catName].push(staticVarPrice[catId[1]]);
	}else if(catName == 'releasedate'){
		urlFinder[catName].push(staticVarDate[catId[1]]);
	}else{		
		urlFinder[catName].push(catId[1]);
		
	}
	//if(catName == 'keyword'){
	  //urlFinder[catName].push();
	//}
	//alert(urlFinder[catName]);
	//alert(modifyUrl);
	var requestUrl = modifyUrl();
	//alert(requestUrl);
	//updateList(requestUrl);	
	updateDatabaseList(requestUrl);
}

/** --------------------Refetch the data and update the listing -------------------*/
function updateList(requestUrl){
	/*-------------------- AJAX REQUEST SEND FOR REQUESTING JSON SEARCH DATA----------*/
	
		// do whatever require with returned data in json
		document.getElementById("hiddenresultListing").innerHTML	= "";	
		$('#hiddenresultListing').append('<div style="width:100%;margin-top:75px;" align="center"><img id="loading" src="'+site_url+'static/images/loading.gif" /></div>');
		$.getJSON(requestUrl, function(data){
				if(data){
					document.getElementById("hiddenresultListing").innerHTML	= "";	
					var jsonDataListing = data.response;
					var element = '';
					$.each(jsonDataListing, function(i,item){
						if(i == 'docs'){
							element += "<table cellpadding='1' cellspacing='0' width='100%' border='0' class='rtd' id='example'><thead><tr><th class='rw' align='left' width='62%' valign='middle'><strong>Title</strong></th><th class='rw' align='left' width='15%' valign='middle'><strong>Price</strong></th><th class='rw' align='left' width='23%' valign='middle'><strong>Release</strong></th></tr></thead><tbody>";
							$.each(item, function(j,itemInnerReport){
							  var dstring = new Date(itemInnerReport.releasedate);
		                                          var strep = dstring.format("mmm,  yyyy");
		                                          
		                                          //Generate Link Here
						  itemTitle=itemInnerReport.text;
						  itemId=itemInnerReport.id;
						  itemTitle=itemTitle.replace(/\./g,"");
						  itemTitle=itemTitle.replace(/&/g,"");
						  itemTitle=itemTitle.replace(/-/,"");
						  itemTitle=itemTitle.replace(/:/g,"");
						  itemTitle=itemTitle.replace(/\(/g,"");
						  itemTitle=itemTitle.replace(/\)/g,"");
						  itemTitle=itemTitle.replace(/   /g," ");
						  itemTitle=itemTitle.replace(/  /g," ");
						  itemTitle=itemTitle.replace(/amp;/g,"");
						  itemTitle=itemTitle.replace(/ /g,"-");
						  itemTitle=itemTitle.replace(/--/g,"-");
						  
						  itemlink=site_url+"report_page/"+itemTitle+"-"+itemId+".html";
		                                          
								element += "<tr class='rrc'><td align='left' width='60%' valign='middle' id='popup' class='cell'><a href='"+itemlink+"' >"+itemInnerReport.text+"<span><div class='popup_left_arrow'></div><br><div class='tl_head_01'>"+itemInnerReport.text+"</div><p><strong>Description</strong>: "+itemInnerReport.summary+"</p><div class='popup_bx_bott'><div class='popup_subbx_left'>Publisher: "+itemInnerReport.publisher+"<br>Product type: "+itemInnerReport.product_type+"<br>Pages: "+itemInnerReport.pages+"</div><div class='popup_subbx_right'>Price 	&#36; "+itemInnerReport.price+"<br><br><button type='submit' class='popup_button' id='"+itemInnerReport.id+"' title='go' onClick='addToCookie('"+'#'+itemInnerReport.id+"')'>Add to wishlist</button></div></div></span></a></td><td align='left' width='15%' valign='middle' class='span_rtd'>&nbsp;$"+itemInnerReport.price+"</td><td align='left' width='23%' valign='middle' class='span_rtd'>"+strep+"</td></tr>";						
							});
							element += "</tbody></table>";
							$('#hiddenresultListing').append(element);					
						}					
					});
				}
				 $('#example').dataTable({"bPaginate": true,"bLengthChange": false,"sPaginationType": "full_numbers"});
			});	
}

/**------------------- Function to remove uri if deselect any criteria -----------------*/
function deleteUri(arraykey,cId){
	removeByValue(arraykey,cId);
	var requestUrl = modifyUrl();	
	return requestUrl;
}
/*
 * update expert listing
 */
var experturi;
function updateExpertList(requestUrl){
experturl=requestUrl;
  //alert("hello");
  // do whatever require with returned data in json
		document.getElementById("hiddenresultListing_experts").innerHTML	= "";	
		$('#hiddenresultListing').append('<div style="width:100%;margin-top:75px;" align="center"><img id="loading" src="'+site_url+'static/images/loading.gif" /></div>');
			$.getJSON(requestUrl, function(data){
	  
			if(data){
			  document.getElementById("hiddenresultListing_experts").innerHTML = "";
				jsonDataExpert = data.response;				
				var element = '';
				//alert(jsonDataExpert.toSource());
				$.each(jsonDataExpert, function(i,item){
					if(i == 'docs'){
						$.each(item, function(j,itemInnerExperts){
						  //alert(itemInnerExperts.id);
						  var photo_url=itemInnerExperts.photo_url;
						  photo_url=photo_url.replace(/ /g,"%20");
							element = "<div class='experts'><a href='"+domain_url+"industry-expert/expert-"+itemInnerExperts.code+"'><img border='0' alt='preview'  src="+photo_url+" width='68px'></a><p style='width:436px; float:right;'><strong><a href='"+domain_url+"industry-expert/expert-"+itemInnerExperts.code+"'>"+itemInnerExperts.code+"</a></strong><br><span class='span_text01'>Expert in "+itemInnerExperts.categoryname+"</span></p><p class='span_text02'></p></div>";					
												
							$('#hiddenresultListing_experts').append(element);
						});
					}					
				});
				
	//initPaginationExperts();

			} else {
			  alert("No data returned");
			  return false;
			}
	});
}
var jsonDataDatabase;
function updateDatabaseList(requestUrl){
  //alert("hello");
  // do whatever require with returned data in json
		document.getElementById("hiddenresultListing_experts").innerHTML= "";	
		//alert(requestUrl);
		$('#hiddenresultListing_experts').append('<div style="width:100%;margin-top:75px;" align="center"><img id="loading" src="'+site_url+'static/images/loading.gif" /></div>');
			$.getJSON(requestUrl, function(data){
			  //alert(data.toString());
	  
			if(data){
			  //alert("hello");
			  document.getElementById("hiddenresultListing_experts").innerHTML = "";
			  //alert(data.response.toString());
				jsonDataDatabase = data.response;				
				var element = '';
			//alert(jsonDataExpert.toSource());
				$.each(jsonDataDatabase.docs, function(i,itemInnerDatabase){
					
						
						  //alert(itemInnerDatabase.id);
							element = "<div class='experts'><a href='database_page?id="+itemInnerDatabase.id+"'></a><p style='width:436px; '><strong><a href='database_page?id="+itemInnerDatabase.id+"'>"+itemInnerDatabase.title+"</a></strong><br><span class='span_text01'>"+itemInnerDatabase.description+"</span></p><p class='span_text02'><i>"+itemInnerDatabase.parameters+"</i></p></div>";					
												
							$('#hiddenresultListing_experts').append(element);
						
					
				});
				
	//initPaginationExperts();

			} else {
			  alert("No data returned");
			  return false;
			}
	});
}
/*
 * function for add to cart
 */
function addToCart(param){
    $.post("includes/addtocart", 
            { id: "2" },
            function(data){alert ('data added'+data);
        });
}

/**------------------- Function to wordwaro funcgiton -----------------*/

String.prototype.wordWrap = function(m, b, c){
	var i, j, l, s, r;
	if(m < 1)
		return this;
	for(i = -1, l = (r = this.split("\n")).length; ++i < l; r[i] += s)
		for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : ""))
			j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length
			|| c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
	return r.join("\n");
};

function createCookie(name,value) {
var days=false;
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}
function Get_Cookie( name ) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ){
        return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ";", len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}


function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

/**-------------------function to count no of items from the cookie -------------------------**/
function countItemCookie(name){
  var len = name.split(",").length;
 /** if(len = 1)
    return 0;
  else
    return len-1;**/
 return len;
  
}
/*
 *
 */
function cartItemCount(){
   var currentReportCookie=Get_Cookie('product_id');
   var len = 0;
   if(currentReportCookie == "" || currentReportCookie == null){
       len = 0;
   } else {
       len = currentReportCookie.split(",").length;
   }
   if(len == '' || len == '0' || len == null || len == 0){
       $('#item_count').html('0');
   } else{
       $('#item_count').html(len);
   }
}

/*
 * function to check a perticular item is present in cookie or not
 * @param it accept the id of the product
 */
function _checkProductInCookie(param){
  var currentReportCookie = '';
  var flag = 1;
  if(Get_Cookie('product_id') == '' || Get_Cookie('product_id') == null){
      currentReportCookie = '';
  } else {
      currentReportCookie=Get_Cookie('product_id');
  }
  var _cookieArray = currentReportCookie.split(",");
  if(_cookieArray != '' || _cookieArray != null){
      for(i = 0; i < _cookieArray.length; i ++){
          if(_cookieArray[i] == param){
              flag = 0;
              break;
          }
      }
  } 
  return flag;
}

function removeDuplicateElement(arrayName)
      {
        var newArray=new Array();
        label:for(var i=0; i<arrayName.length;i++ )
        {  
          for(var j=0; j<newArray.length;j++ )
          {
            if(newArray[j]==arrayName[i]) 
            continue label;
          }
          newArray[newArray.length] = arrayName[i];
        }
        return newArray;
      }
function _checkSearchTextInCookie(param){
  var currentReportCookie = '';
  var flag = 1;
  if(Get_Cookie('search_string') == '' || Get_Cookie('search_string') == null){
      currentReportCookie = '';
  } else {
      currentReportCookie=Get_Cookie('search_string');
  }
  var _cookieArray = currentReportCookie.split(",");
  if(_cookieArray != '' || _cookieArray != null){
      for(i = 0; i < _cookieArray.length; i ++){
          if(_cookieArray[i] == param){
              flag = 0;
              break;
          }
      }
  } 
  return flag;
}
function _checkRecentViewInCookie(param){
  var currentRecentViewCookie = '';
  var flag = 1;
  if(Get_Cookie('recent_view') == '' || Get_Cookie('recent_view') == null){
      currentRecentViewCookie = '';
  } else {
      currentRecentViewCookie=Get_Cookie('recent_view');
  }
  var _cookieArray = currentRecentViewCookie.split(" OR ");
  if(_cookieArray != '' || _cookieArray != null){
      for(i = 0; i < _cookieArray.length; i ++){
          if(_cookieArray[i] == param){
              flag = 0;
              break;
          }
      }
  } 
  return flag;
}
function _checkRecentViewExpertInCookie(param){
  var currentRecentViewExpertCookie = '';
  var flag = 1;
  if(Get_Cookie('recent_view_expert') == '' || Get_Cookie('recent_view_expert') == null){
      currentRecentViewExpertCookie = '';
  } else {
      currentRecentViewExpertCookie=Get_Cookie('recent_view_expert');
  }
  var _cookieArray = currentRecentViewExpertCookie.split(" OR ");
  if(_cookieArray != '' || _cookieArray != null){
      for(i = 0; i < _cookieArray.length; i ++){
          if(_cookieArray[i] == param){
              flag = 0;
              break;
          }
      }
  } 
  return flag;
}
function _checkValueInArray(param,val){
  var flag = true;
  
  for(i = 0; i< param.length; i++){
    
    if(param[i]== val)
      flag=false
      break;
  }
  return flag;
  
}
/*
 * function to change the text of already added item in the wish list
 * @param it accept an id of the division where the content is to be replaced
 */
function changeContentOfAlreadyAddedProduct(param,id){
    if(_checkProductInCookie(id) == 0)
        $(param).html("Already Added");
    else
        $(param).html("Add to Wishlist");
}
/*
 * function to remove an item from the cookie
 * @param product_id
 */
function _removeItemFromCookie(param){
  var currentReportCookie = '';
  
  if(Get_Cookie('product_id') == '' || Get_Cookie('product_id') == null){
      currentReportCookie = '';
  } else {
      currentReportCookie=Get_Cookie('product_id');
  }
  var _cookieArray = currentReportCookie.split(",");
  var tempArray = '';
  for(i = 0; i < _cookieArray.length; i++){
          if(_cookieArray[i] != param){
	     if(tempArray ==''  || tempArray == null){
                    
                    tempArray = _cookieArray[i];
                    
                } else{
                    
                    tempArray = tempArray+','+_cookieArray[i]
                    
                }
              
            }
      }
      eraseCookie('product_id');
      createCookie('product_id', tempArray);
      return 1
}
/*
 * function to add item product ids into the cookie
 * @param it accepts document id
 */
function addToCookie(param,id){
    var product_id=id;
    var user='';
    var cok = '';
    var item = '';
    var newReportCookie = '';
    var currentReportCookie ='';
    var addtowishlist_url=document.location.host+'/addtocart';
    
    //Check if already added
	    var product_id_cookie=readCookie('product_id');
	    var id_exists=false;
	    if(product_id_cookie=='' && product_id_cookie == null){
	    product_id_cookie_array=product_id_cookie.split(",");
	    }
	    else{
	      product_id_cookie_array = '';
	    }
	    for(var i=0;i<=product_id_cookie_array.length;i++){
		if(product_id_cookie_array[i]==id){
		    id_exists=true;
		}
	    }
	    if(id_exists){
		postActionCallback();
	    }
	    else{
    
    
    $.get("http://"+addtowishlist_url+"?product_id="+product_id+"&user="+user,function(data){
        if(data==1){
            $(param).html("Added");
            currentReportCookie=Get_Cookie('product_id');
	    
	    
	  
            if( _checkProductInCookie(id) == 1){
                eraseCookie('product_id');
                if(currentReportCookie ==''  || currentReportCookie == null){
                    createCookie('product_id',id);
                    $('#item_count').html('');
                    $('#item_count').append('1');
                } else{
                    newReportCookie  = currentReportCookie+","+id;
                    createCookie('product_id',newReportCookie);
                    var len = newReportCookie.split(",").length;
                    $('#item_count').html('');
                    $('#item_count').append(len);
                }
            } else {
                //alert('Already Added');
            }
            postActionCallback();
        } else{	
            alert("Error sending request. Please try again after some time");
        }
    });
	    }
return true;
}
/*
 *function to add searched text into the cookie
 */
function _addToCookieSearchText(param){
  var currentSearchCookie = '';
  currentSearchCookie=Get_Cookie('search_string');
  if(_checkSearchTextInCookie(param)==1){
    eraseCookie('search_string');
                if(currentSearchCookie ==''  || currentSearchCookie == null){
                    createCookie('search_string',param);
                    
                } else{
                    newSearchCookie  = currentSearchCookie+","+param;
                    createCookie('search_string',newSearchCookie);
		}    
  } else {
      //alert("already Added");
  }
}
/*
 *function to store recentrly viewed
 */
function _addToCookieRecentView(param){
  var currentRecentViewCookie = '';
  currentRecentViewCookie=Get_Cookie('recent_view');
  if(_checkRecentViewInCookie(param)==1){
    eraseCookie('recent_view');
                if(currentRecentViewCookie ==''  || currentRecentViewCookie == null){
                    createCookie('recent_view',param);
                    
                } else{
                    newRecentViewCookie  = currentRecentViewCookie+" OR "+param;
                    createCookie('recent_view',newRecentViewCookie);
		}    
  } else {
      //alert("already Added");
  }
}
/*
 *function to store recentrly viewed experts
 */
function _addToCookieRecentViewExpert(param){
  var currentRecentViewExpertCookie = '';
  currentRecentViewExpertCookie=Get_Cookie('recent_view_expert');
  if(_checkRecentViewExpertInCookie(param)==1){
    eraseCookie('recent_view_expert');
                if(currentRecentViewExpertCookie ==''  || currentRecentViewExpertCookie == null){
                    createCookie('recent_view_expert',param);
                    
                } else{
                    newRecentViewExpertCookie  = currentRecentViewExpertCookie+" OR "+param;
                    createCookie('recent_view_expert',newRecentViewExpertCookie);
		}    
  } else {
      //alert("already Added");
  }
}
/*
 * function to get q from the search url
 */
function gupSearch( name, url )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
    return "";
  else
    return results[1];
}

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};


/*!
 * jQuery corner plugin: simple corner rounding
 * Examples and documentation at: http://jquery.malsup.com/corner/
 * version 2.11 (15-JUN-2010)
 * Requires jQuery v1.3.2 or later
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Authors: Dave Methvin and Mike Alsup
 */

/**
 *  corner() takes a single string argument:  $('#myDiv').corner("effect corners width")
 *
 *  effect:  name of the effect to apply, such as round, bevel, notch, bite, etc (default is round). 
 *  corners: one or more of: top, bottom, tr, tl, br, or bl.  (default is all corners)
 *  width:   width of the effect; in the case of rounded corners this is the radius. 
 *           specify this value using the px suffix such as 10px (yes, it must be pixels).
 */
;(function($) { 

var style = document.createElement('div').style,
    moz = style['MozBorderRadius'] !== undefined,
    webkit = style['WebkitBorderRadius'] !== undefined,
    radius = style['borderRadius'] !== undefined || style['BorderRadius'] !== undefined,
    mode = document.documentMode || 0,
    noBottomFold = $.browser.msie && (($.browser.version < 8 && !mode) || mode < 8),

    expr = $.browser.msie && (function() {
        var div = document.createElement('div');
        try { div.style.setExpression('width','0+0'); div.style.removeExpression('width'); }
        catch(e) { return false; }
        return true;
    })();

$.support = $.support || {};
$.support.borderRadius = moz || webkit || radius; // so you can do:  if (!$.support.borderRadius) $('#myDiv').corner();

function sz(el, p) { 
    return parseInt($.css(el,p))||0; 
};
function hex2(s) {
    var s = parseInt(s).toString(16);
    return ( s.length < 2 ) ? '0'+s : s;
};
function gpc(node) {
    while(node) {
        var v = $.css(node,'backgroundColor'), rgb;
        if (v && v != 'transparent' && v != 'rgba(0, 0, 0, 0)') {
            if (v.indexOf('rgb') >= 0) { 
                rgb = v.match(/\d+/g); 
                return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
            }
            return v;
        }
        if (node.nodeName.toLowerCase() == 'html')
            break;
        node = node.parentNode; // keep walking if transparent
    }
    return '#ffffff';
};

function getWidth(fx, i, width) {
    switch(fx) {
    case 'round':  return Math.round(width*(1-Math.cos(Math.asin(i/width))));
    case 'cool':   return Math.round(width*(1+Math.cos(Math.asin(i/width))));
    case 'sharp':  return Math.round(width*(1-Math.cos(Math.acos(i/width))));
    case 'bite':   return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
    case 'slide':  return Math.round(width*(Math.atan2(i,width/i)));
    case 'jut':    return Math.round(width*(Math.atan2(width,(width-i-1))));
    case 'curl':   return Math.round(width*(Math.atan(i)));
    case 'tear':   return Math.round(width*(Math.cos(i)));
    case 'wicked': return Math.round(width*(Math.tan(i)));
    case 'long':   return Math.round(width*(Math.sqrt(i)));
    case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
    case 'dogfold':
    case 'dog':    return (i&1) ? (i+1) : width;
    case 'dog2':   return (i&2) ? (i+1) : width;
    case 'dog3':   return (i&3) ? (i+1) : width;
    case 'fray':   return (i%2)*width;
    case 'notch':  return width; 
    case 'bevelfold':
    case 'bevel':  return i+1;
    }
};

$.fn.corner = function(options) {
    // in 1.3+ we can fix mistakes with the ready state
    if (this.length == 0) {
        if (!$.isReady && this.selector) {
            var s = this.selector, c = this.context;
            $(function() {
                $(s,c).corner(options);
            });
        }
        return this;
    }

    return this.each(function(index){
        var $this = $(this),
            // meta values override options
            o = [$this.attr($.fn.corner.defaults.metaAttr) || '', options || ''].join(' ').toLowerCase(),
            keep = /keep/.test(o),                       // keep borders?
            cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]),  // corner color
            sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]),  // strip color
            width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10, // corner width
            re = /round|bevelfold|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dogfold|dog/,
            fx = ((o.match(re)||['round'])[0]),
            fold = /dogfold|bevelfold/.test(o),
            edges = { T:0, B:1 },
            opts = {
                TL:  /top|tl|left/.test(o),       TR:  /top|tr|right/.test(o),
                BL:  /bottom|bl|left/.test(o),    BR:  /bottom|br|right/.test(o)
            },
            // vars used in func later
            strip, pad, cssHeight, j, bot, d, ds, bw, i, w, e, c, common, $horz;
        
        if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
            opts = { TL:1, TR:1, BL:1, BR:1 };
            
        // support native rounding
        if ($.fn.corner.defaults.useNative && fx == 'round' && (radius || moz || webkit) && !cc && !sc) {
            if (opts.TL)
                $this.css(radius ? 'border-top-left-radius' : moz ? '-moz-border-radius-topleft' : '-webkit-border-top-left-radius', width + 'px');
            if (opts.TR)
                $this.css(radius ? 'border-top-right-radius' : moz ? '-moz-border-radius-topright' : '-webkit-border-top-right-radius', width + 'px');
            if (opts.BL)
                $this.css(radius ? 'border-bottom-left-radius' : moz ? '-moz-border-radius-bottomleft' : '-webkit-border-bottom-left-radius', width + 'px');
            if (opts.BR)
                $this.css(radius ? 'border-bottom-right-radius' : moz ? '-moz-border-radius-bottomright' : '-webkit-border-bottom-right-radius', width + 'px');
            return;
        }
            
        strip = document.createElement('div');
        $(strip).css({
            overflow: 'hidden',
            height: '1px',
            minHeight: '1px',
            fontSize: '1px',
            backgroundColor: sc || 'transparent',
            borderStyle: 'solid'
        });
    
        pad = {
            T: parseInt($.css(this,'paddingTop'))||0,     R: parseInt($.css(this,'paddingRight'))||0,
            B: parseInt($.css(this,'paddingBottom'))||0,  L: parseInt($.css(this,'paddingLeft'))||0
        };

        if (typeof this.style.zoom != undefined) this.style.zoom = 1; // force 'hasLayout' in IE
        if (!keep) this.style.border = 'none';
        strip.style.borderColor = cc || gpc(this.parentNode);
        cssHeight = $(this).outerHeight();

        for (j in edges) {
            bot = edges[j];
            // only add stips if needed
            if ((bot && (opts.BL || opts.BR)) || (!bot && (opts.TL || opts.TR))) {
                strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
                d = document.createElement('div');
                $(d).addClass('jquery-corner');
                ds = d.style;

                bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);

                if (bot && cssHeight != 'auto') {
                    if ($.css(this,'position') == 'static')
                        this.style.position = 'relative';
                    ds.position = 'absolute';
                    ds.bottom = ds.left = ds.padding = ds.margin = '0';
                    if (expr)
                        ds.setExpression('width', 'this.parentNode.offsetWidth');
                    else
                        ds.width = '100%';
                }
                else if (!bot && $.browser.msie) {
                    if ($.css(this,'position') == 'static')
                        this.style.position = 'relative';
                    ds.position = 'absolute';
                    ds.top = ds.left = ds.right = ds.padding = ds.margin = '0';
                    
                    // fix ie6 problem when blocked element has a border width
                    if (expr) {
                        bw = sz(this,'borderLeftWidth') + sz(this,'borderRightWidth');
                        ds.setExpression('width', 'this.parentNode.offsetWidth - '+bw+'+ "px"');
                    }
                    else
                        ds.width = '100%';
                }
                else {
                    ds.position = 'relative';
                    ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' : 
                                        (pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';                
                }

                for (i=0; i < width; i++) {
                    w = Math.max(0,getWidth(fx,i, width));
                    e = strip.cloneNode(false);
                    e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
                    bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
                }
                
                if (fold && $.support.boxModel) {
                    if (bot && noBottomFold) continue;
                    for (c in opts) {
                        if (!opts[c]) continue;
                        if (bot && (c == 'TL' || c == 'TR')) continue;
                        if (!bot && (c == 'BL' || c == 'BR')) continue;
                        
                        common = { position: 'absolute', border: 'none', margin: 0, padding: 0, overflow: 'hidden', backgroundColor: strip.style.borderColor };
                        $horz = $('<div/>').css(common).css({ width: width + 'px', height: '1px' });
                        switch(c) {
                        case 'TL': $horz.css({ bottom: 0, left: 0 }); break;
                        case 'TR': $horz.css({ bottom: 0, right: 0 }); break;
                        case 'BL': $horz.css({ top: 0, left: 0 }); break;
                        case 'BR': $horz.css({ top: 0, right: 0 }); break;
                        }
                        d.appendChild($horz[0]);
                        
                        var $vert = $('<div/>').css(common).css({ top: 0, bottom: 0, width: '1px', height: width + 'px' });
                        switch(c) {
                        case 'TL': $vert.css({ left: width }); break;
                        case 'TR': $vert.css({ right: width }); break;
                        case 'BL': $vert.css({ left: width }); break;
                        case 'BR': $vert.css({ right: width }); break;
                        }
                        d.appendChild($vert[0]);
                    }
                }
            }
        }
    });
};

$.fn.uncorner = function() { 
    if (radius || moz || webkit)
        this.css(radius ? 'border-radius' : moz ? '-moz-border-radius' : '-webkit-border-radius', 0);
    $('div.jquery-corner', this).remove();
    return this;
};

// expose options
$.fn.corner.defaults = {
    useNative: true, // true if plugin should attempt to use native browser support for border radius rounding
    metaAttr:  'data-corner' // name of meta attribute to use for options
};
    
})(jQuery);

