﻿var _displayThumbs = $("#displayThumbs").attr('value');
var _currentResults = new Array();
var _resultContent;
var _search_api_url = "/API/Search/DataAPI-exalead.aspx";

var StoreResult=new Array();
var _nofpageview=0;
var _noppageview=0;
var _currentpageindex=0;
var _fetchedpageindex=0;
var _isfreshsearch=1;
var _startfetchedpageindex=0;
var _toSearchIndex='0';

// Functions
function OnWSRequestFailed(error)
{ 
    //fcnShowHideSearching('error');           
}

function DoSearch(oSearch)
{
    _toSearchIndex=oSearch.pSearchEngineStartIndex;
    fcnShowHideSearching('button');
    fcnGetSearchTerms(oSearch);
    runSearch(oSearch);
    if(_toSearchIndex!='0'){    
        fcnFirstPrevRequests(oSearch);
    }
    else {   
        fcnFirstRequests(oSearch);
    }   
}

function runSupplementalSearch(oSearch)
{
    WebSearch.ajxSearch.GetSearchCount(oSearch, OnWSRequestComplete2, OnWSRequestFailed2);
}

function fcnFirstRequests(oSearch)
{    
    if(_nofpageview==1){
    return;
    }
    else if(_nofpageview==0){
    _nofpageview=parseInt($('#hdnpagecount').val()); 
    }
    else{
    _nofpageview=_nofpageview-1;
    }
    oSearch.pPreviousSearch = 'False';
    oSearch.pSearchEngineStartIndex=(parseInt(oSearch.pSearchEngineStartIndex)+parseInt($('#ctl00_ContentArea_SearchResultsControlV3_cboResultCount').val())).toString();
    WebSearch.ajxSearch.GetSearchResults(oSearch, OnWSRequestCompleteFirst, OnWSRequestFailed,oSearch);
}

function fcnFirstPrevRequests(_oSearch)
{
    if(_oSearch.pSearchEngineStartIndex!='0'){
        if(_noppageview==1){
        _oSearch.pSearchEngineStartIndex=_toSearchIndex;
        fcnFirstRequests(_oSearch);
        return;
        }
        else if(_noppageview==0){
        _noppageview=parseInt($('#hdnpagecount').val()); 
        }
        else{
        _noppageview=_noppageview-1;
        }
        _oSearch.pPreviousSearch = 'False';
        _oSearch.pSearchEngineStartIndex=(parseInt(_oSearch.pSearchEngineStartIndex)-parseInt($('#ctl00_ContentArea_SearchResultsControlV3_cboResultCount').val())).toString();
        WebSearch.ajxSearch.GetSearchResults(_oSearch, OnWSRequestCompletePreviousFirst, OnWSRequestFailed,_oSearch);
    }
    else
    {
        _oSearch.pSearchEngineStartIndex=_toSearchIndex;
        oSearch.pSearchEngineStartIndex=_toSearchIndex;
        fcnFirstRequests(_oSearch);
    }
}

function fcnCustomRequests(oSearch)
{   
    oSearch.pPreviousSearch = 'False';
    WebSearch.ajxSearch.GetSearchResults(oSearch, OnWSRequestCompleteCustom, OnWSRequestFailed);
}

function runSearch(oSearch)
{   
    oSearch.pPreviousSearch = 'False';
    WebSearch.ajxSearch.GetSearchResults(oSearch, OnWSRequestComplete, OnWSRequestFailed);
}

function OnWSRequestComplete2(results)
{
    // 6/12/2009 jao - added 2nd web request complete callback handler
    var SecondaryResults = $get('SecondarySearchCount');
    var SecondaryResults2 = $get('SecondarySearchCount2');
    SecondaryResults.innerHTML = '<strong>' + results + '</strong>&nbsp;';
}

function serpLockdown(pid) {
	if (pid) {
		$("#serp_lockdown .teaser-image-preview").html(getSERPPreviewImage(pid));
		$("#serp_lockdown .teaser-image-meta").html(getSERPPreviewMeta(pid));
	}
	$("#serp_lockdown").dialog('open');
}

function serpUpgradeLockdown(pid) {
	if (pid) {
		$("#upgrade_required .teaser-image-preview").html(getSERPPreviewImage(pid));
		$("#upgrade_required .teaser-image-meta").html(getSERPPreviewMeta(pid));
	}
	$("#upgrade_required").dialog('open');
}

function buildPreview(id) {
	var top = "<div class=\"top\"></div>";
	var bottom = "<div class=\"bottom\"></div>";
	var content = "<div class=\"content\" style=\"position: relative; height: 310px; width: 250px;\"><div class=\"loading\" style=\"text-align: center; height: 288px; position: absolute; z-index: 1000;\"><img class=\"preview-image\" alt=\"loading...\" src=\"/images/ajax-loader.gif\" style='vertical-align: middle;' /> Image loading</div><div style=\"text-align: center; height: 288px; position: absolute; z-index: 1000;\" id=\""+id+"_teaser_image\" class=\"teaser-image\"></div></div>";
	var html = "<div class=\"results-preview ui-corner-all\" style=\"display: none; background-color: #ECE6C2; border: 1px solid #6E2208; margin-top: 10px;\" id=\"preview_"+id+"\">"+top+content+bottom+"</div>";
	return html;
}

function OnWSRequestFailed3(error)
{ 
    //alert(error);
    //fcnShowHideSearching('error');           
}
function OnWSRequestComplete3(results)
{
    // 7/1/2009 jel - added 3rd web request complete callback handler
    $('#teaser_ln_results_count').html('<strong>' + results + '</strong>');
    $('#teaser_ln_results_term').html('<strong>' + getQueryVariable("lname") + '</strong>');
	if ($("#h3LastNameArea:hidden")) $('#h3LastNameArea').removeClass('hidden').show();
}
function runLastNameSearch(oSearch)
{
    WebSearch.ajxSearch.GetSearchCount(oSearch, OnWSRequestComplete3, OnWSRequestFailed3);
}

function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		  var pair = vars[i].split("=");
		  if (pair[0] == variable) {
		  return pair[1];
		  }
	}
	return false;
}

function getSERPPreviewImage(id) {
	var imagePreview = "<img src=\""+_search_api_url+"?search=IMAGEID:"+id+";&returns=THUMB;\" style=\"width: 240px;\" />";
	return imagePreview;
}

function getSERPPreviewMeta(id) {
	var metaPreview = $("a#"+id).parent().parent().find(".result-options span").html();
	return metaPreview;
}

function OnWSRequestComplete(results) { 
	// If there are results...
    if (results.pNumberOfNAResults != "0") {
		
		// Show the results of the search
		fcnShowHideSearching('done');
		var noFreeFrontPage = $get('divNoFrontPageResults');
		var r_container = $('#divResultsContainer');
		var NavBottom = $get('divNavBottom');
		var NavTop = $get('divNavTop');
		var CurrentContent = $get('lblCurrentViewingContent');
		var NumberOfNAResults = $get('lblNumberOfNAResults');
		var SearchTerms = $get('lblSearchTerms');
		var SearchTerms2 = $get('lblSearchTerms2'); 
		
		var NarrowedBy = $get('spnNarrowedBy');
		var NarrowedBy2 = $get('spnNarrowedBy2');
		var SaveSearch = $get('lnkSaveSearch');
		var SelectedResults = $get('lnkSaveSelectedResults');
		var tdNarrow = $get('trNarrow');
		var tdNarrow2 = $get('trNarrow2');
		var tdSaveResults = $get('tdSaveResults');
		
		var _pgindx=0;
//        CurrentContent.innerHTML = results.pContent;        
        var arrindex = results.pCurrentContent.split("-");
        if(arrindex.length>0)
        {
            _pgindx=fcnGetArrayIndex(parseInt(arrindex[0]));
            _currentpageindex=_pgindx;
            _fetchedpageindex=_pgindx;
            _startfetchedpageindex=_pgindx;
        }
        if(StoreResult[_pgindx]==null)
        {
            StoreResult[_pgindx]=results;
        }
        else if(StoreResult.length>_pgindx)
        {
            StoreResult[_pgindx]=results;
        }
        else if(StoreResult.length<_pgindx)
        {
            var _xtraelements=_pgindx-StoreResult.length;
            for(var i=0; i<_xtraelements;i++)
            {
                if(StoreResult[i]=='undefined'){
                StoreResult[i]="";} 
            }
            StoreResult[_pgindx]=results;
        }  
			
		r_container.html(results.pContent);
		NavBottom.innerHTML = results.pNav;
		NavTop.innerHTML = results.pNav;
		CurrentContent.innerHTML = results.pCurrentContent + ' ';
		NumberOfNAResults.innerHTML = results.pNumberOfNAResults + ' ';
		// 12/29/2009 jao - added string replacements below
		SearchTerms.innerHTML = results.pSearchTerms.replace('!(!', '(').replace('!)!', ')');
		SearchTerms2.innerHTML = results.pSearchTerms.replace('!(!', '(').replace('!)!', ')');
		// 6/12/2009 jao - Updated messages below per Jeff K.'s request
		
		
		NarrowedBy.innerHTML = results.pNarrowedBy;
		NarrowedBy2.innerHTML = results.pNarrowedBy;        
		if (NarrowedBy.innerHTML != '')
			tdNarrow.className = '';
		else
			tdNarrow.className = 'hidden';
			
		if (NarrowedBy2.innerHTML != '')
			tdNarrow2.className = '';
		else
			tdNarrow2.className = 'hidden';
				
		tdSaveResults.visible = results.pFullAcess;
		SaveSearch.href = results.pSaveSearch;
		
		var resultLinks = $(".result-link", results.pContent);
		resultLinks.each(function() {
			_currentResults.push($(this).attr('id'));
		});
		
		_resultContent = results.pContent;
				
		// Regex to match classes for premium content
		var rContentPremium = /^(.*)class=["|']content-premium(.*)$/m;
		var rIconPremium = /^(.*)class=["|']icon-premium(.*)$/m;

		// Check to see if the user is anonymous and has not checked Front Pages Only
		if (_userclass == "anonymous" && results.NoFrontPageResults != "false")
 		{
			// Check to see if the search results string has any matches for premium content
			if (results.pContent.match(rContentPremium) || results.pContent.match(rIconPremium)) {
				// Check if the query string contains the fname and lname params and if the Last Name span has already been shown
				if ($("#h3LastNameArea").hasClass('hidden') && window.location.href.indexOf("fname") != -1 && window.location.href.indexOf("lname") != -1) {
					var oSearch = new objSearch();
					var lname = getQueryVariable("lname");
					oSearch.pSearch = lname;
					runLastNameSearch(oSearch);
				} else { // This is a second run search and the Last Name span gets hidden
					if ($("#h3LastNameArea:visible")) $("#h3LastNameArea").hide();
				}
			var id = $("a.result-link:first", results.pContent).attr('id');
			var t = setTimeout("serpLockdown("+id+")", 400);
			$("#teaser_image_results_count").html("1");
			$("#teaser_image_results_page_total").html(10);
			$("#spnSearchResults").html(results.pNumberOfNAResults + ' ');
			// 12/29/2009 jao - added string replacement below
			$("#teaserSearchTerms").html(results.pSearchTerms.replace('!(!','(').replace('!)!',')'));
			} else {
				$('.content-tih .result-link, .content-front .result-link').each(function() {
					$(this).attr('href','http://www.newspaperarchive.com/register/premium.aspx');
				});
			}
			$('.content-premium .result-link, content-standard .result-link').each(function() {
				$(this).click(function() {
					serpLockdown();
					return false;
				});
				$(this).attr('href','http://www.newspaperarchive.com/register/premium.aspx');
			});
		} else if (_userclass == "free") {
						
			$('.content-premium .result-link').each(function() {
				var id = $(this).attr('id');
				$(this).click(function() {
					serpUpgradeLockdown(id);
					return false;
				});
			});
			
			if (results.NoFrontPageResults == "true") {
				$("#message_results_no_front_pages").html("Your search for <strong>"+results.pSearchTerms+"</strong> did not appear in any of our <strong>Front Pages</strong>, but we have discovered <strong>"+results.pNumberOfNAResults+"</strong> results in other newspaper pages found in our archives! We've included these results below for you to preview.").show();
			} else if (results.NoFrontPageResults == "false") {
				$("#message_results_no_front_pages").html("We discovered <strong>"+results.pNumberOfNAResults+"</strong> results for <strong>"+results.pSearchTerms+"</strong> in  our <strong>Front Pages</strong>. However, there are <span id='SecondarySearchCount'></span> additional results in other newspaper pages found in our complete archive! <a href='#' onclick=\"$('#ctl00_ContentArea_SearchResultsControlV3_ucRefineKeywords_search_refine_front_only').click();$('#ctl00_ContentArea_SearchResultsControlV3_btnNarrowResults').click();return false;\">Click here</a> to see all of the <span id='SecondarySearchCount2'></span>results.").show();
				var oSearch = new objSearch();
				oSearch.FrontPage = "false";
				// 12/29/2009 jao - added string replacement below
				oSearch.pSearch = results.pSearchTerms.replace('!(!','(').replace('!)!',')');
				runSupplementalSearch(oSearch);
			} else if (results.NoFrontPageResults == "" || results.NoFrontPageResults == null || results.NoFrontPageResults == undefined) {
				$("#message_results_no_front_pages").hide();
			}
		} else if (_userclass == "premium") {
		}
		if (_displayThumbs == 'true') {
			$('a.result-link').each(function() {
				var href = $(this).attr('href');
				var id = $(this).attr('id');
					preview = buildPreview(id);					  
				$(this).parent().append(preview);
			});
			
			$('h3.result-title').mouseover(function() {
				var href = $(this).find('a.result-link').attr('href');
				var id = $(this).find('a.result-link').attr('id');
				var html = "<a class=\"preview-image-link\" style=\"display: block;\" href=\"#\">"+getSERPPreviewImage(id)+"</a>"
				$('.results-preview').hide();
				$(this).find('.results-preview').show();
				if ($(this).find('.teaser-image').html() == "") {
					$(this).find('.teaser-image').html(html);
					$(this).find('.teaser-image').show();
				}
			}).mouseout(function() {
				$(this).find('.results-preview').hide();
			});
		}
		$('h3.result-title a').each(function() {
				//var href = $(this).attr('href','/PdfViewerTags.aspx?img='+$(this).attr('id').toString()+'&firstvisit=true&src=search&currentResult=1');				
		});
		SetNewViewer();
	} else {
        // If there are no results...
        var SearchTerms = $get('lblSearchTerms'); 
        var SearchTerms2 = $get('lblSearchTerms2');
        // 12/29/2009 jao - added string replacement below
        SearchTerms.innerHTML = results.pSearchTerms.replace('!(!','(').replace('!)!',')');
        SearchTerms2.innerHTML = results.pSearchTerms.replace('!(!','(').replace('!)!',')');
        // G Davis, Sept 18, 2009 - adding references to the labels intended to
        // display the record range and the total number of records after 
        // the search is complete - in case nothing is found, both need to be set to 0 (zero)
        var CurrentContent = $get('lblCurrentViewingContent');
        var NumberOfNAResults = $get('lblNumberOfNAResults');
        CurrentContent.innerHTML = '0 ';
        NumberOfNAResults.innerHTML = '0 ';
          
        fcnShowHideSearching('noresults');
    }
}

/* mod */
function fcnGetArrayResult(results)
{  
    // If there are results...
    if (results.pNumberOfNAResults != "0") {
		
		fcnShowHideSearching('done');
		var noFreeFrontPage = $get('divNoFrontPageResults');
		var r_container = $('#divResultsContainer');
		var NavBottom = $get('divNavBottom');
		var NavTop = $get('divNavTop');
		var CurrentContent = $get('lblCurrentViewingContent');
		var NumberOfNAResults = $get('lblNumberOfNAResults');
		var SearchTerms = $get('lblSearchTerms');
		var SearchTerms2 = $get('lblSearchTerms2'); 
		
		var NarrowedBy = $get('spnNarrowedBy');
		var NarrowedBy2 = $get('spnNarrowedBy2');
		var SaveSearch = $get('lnkSaveSearch');
		var SelectedResults = $get('lnkSaveSelectedResults');
		var tdNarrow = $get('trNarrow');
		var tdNarrow2 = $get('trNarrow2');
		var tdSaveResults = $get('tdSaveResults');
		
		r_container.html(results.pContent);
		NavBottom.innerHTML = results.pNav;
		NavTop.innerHTML = results.pNav;
		CurrentContent.innerHTML = results.pCurrentContent + ' ';
		NumberOfNAResults.innerHTML = results.pNumberOfNAResults + ' ';
		// 12/29/2009 jao - added string replacements below
		SearchTerms.innerHTML = results.pSearchTerms.replace('!(!', '(').replace('!)!', ')');
		SearchTerms2.innerHTML = results.pSearchTerms.replace('!(!', '(').replace('!)!', ')');
		// 6/12/2009 jao - Updated messages below per Jeff K.'s request
		
		NarrowedBy.innerHTML = results.pNarrowedBy;
		NarrowedBy2.innerHTML = results.pNarrowedBy;        
		if (NarrowedBy.innerHTML != '')
			tdNarrow.className = '';
		else
			tdNarrow.className = 'hidden';
			
		if (NarrowedBy2.innerHTML != '')
			tdNarrow2.className = '';
		else
			tdNarrow2.className = 'hidden';
				
		tdSaveResults.visible = results.pFullAcess;
		SaveSearch.href = results.pSaveSearch;
		
		var resultLinks = $(".result-link", results.pContent);
		resultLinks.each(function() {
			_currentResults.push($(this).attr('id'));
		});
		
		_resultContent = results.pContent;
				
		// Regex to match classes for premium content
		var rContentPremium = /^(.*)class=["|']content-premium(.*)$/m;
		var rIconPremium = /^(.*)class=["|']icon-premium(.*)$/m;

		// Check to see if the user is anonymous and has not checked Front Pages Only
		if (_userclass == "anonymous" && results.NoFrontPageResults != "false")
 		{
			// Check to see if the search results string has any matches for premium content
			if (results.pContent.match(rContentPremium) || results.pContent.match(rIconPremium)) {
				// Check if the query string contains the fname and lname params and if the Last Name span has already been shown
				if ($("#h3LastNameArea").hasClass('hidden') && window.location.href.indexOf("fname") != -1 && window.location.href.indexOf("lname") != -1) {
					var oSearch = new objSearch();
					var lname = getQueryVariable("lname");
					oSearch.pSearch = lname;
					runLastNameSearch(oSearch);
				} else { // This is a second run search and the Last Name span gets hidden
					if ($("#h3LastNameArea:visible")) $("#h3LastNameArea").hide();
				}
			var id = $("a.result-link:first", results.pContent).attr('id');
			var t = setTimeout("serpLockdown("+id+")", 400);
			$("#teaser_image_results_count").html("1");
			$("#teaser_image_results_page_total").html(10);
			$("#spnSearchResults").html(results.pNumberOfNAResults + ' ');
			// 12/29/2009 jao - added string replacement below
			$("#teaserSearchTerms").html(results.pSearchTerms.replace('!(!','(').replace('!)!',')'));
			} else {
				$('.content-tih .result-link, .content-front .result-link').each(function() {
					$(this).attr('href','http://www.newspaperarchive.com/register/premium.aspx');
				});
			}
			$('.content-premium .result-link, content-standard .result-link').each(function() {
				$(this).click(function() {
					serpLockdown();
					return false;
				});
				$(this).attr('href','http://www.newspaperarchive.com/register/premium.aspx');
			});
		} else if (_userclass == "free") {
						
			$('.content-premium .result-link').each(function() {
				var id = $(this).attr('id');
				$(this).click(function() {
					serpUpgradeLockdown(id);
					return false;
				});
			});
			
			if (results.NoFrontPageResults == "true") {
				$("#message_results_no_front_pages").html("Your search for <strong>"+results.pSearchTerms+"</strong> did not appear in any of our <strong>Front Pages</strong>, but we have discovered <strong>"+results.pNumberOfNAResults+"</strong> results in other newspaper pages found in our archives! We've included these results below for you to preview.").show();
			} else if (results.NoFrontPageResults == "false") {
				$("#message_results_no_front_pages").html("We discovered <strong>"+results.pNumberOfNAResults+"</strong> results for <strong>"+results.pSearchTerms+"</strong> in  our <strong>Front Pages</strong>. However, there are <span id='SecondarySearchCount'></span> additional results in other newspaper pages found in our complete archive! <a href='#' onclick=\"$('#ctl00_ContentArea_SearchResultsControlV3_ucRefineKeywords_search_refine_front_only').click();$('#ctl00_ContentArea_SearchResultsControlV3_btnNarrowResults').click();return false;\">Click here</a> to see all of the <span id='SecondarySearchCount2'></span>results.").show();
				var oSearch = new objSearch();
				oSearch.FrontPage = "false";
				// 12/29/2009 jao - added string replacement below
				oSearch.pSearch = results.pSearchTerms.replace('!(!','(').replace('!)!',')');
				runSupplementalSearch(oSearch);
			} else if (results.NoFrontPageResults == "" || results.NoFrontPageResults == null || results.NoFrontPageResults == undefined) {
				$("#message_results_no_front_pages").hide();
			}
		} else if (_userclass == "premium") {
		}
		if (_displayThumbs == 'true') {
			$('a.result-link').each(function() {
				var href = $(this).attr('href');
				var id = $(this).attr('id');
					preview = buildPreview(id);					  
				$(this).parent().append(preview);
			});
			
			$('h3.result-title').mouseover(function() {
				var href = $(this).find('a.result-link').attr('href');
				var id = $(this).find('a.result-link').attr('id');
				var html = "<a class=\"preview-image-link\" style=\"display: block;\" href=\"#\">"+getSERPPreviewImage(id)+"</a>"
				$('.results-preview').hide();
				$(this).find('.results-preview').show();
				if ($(this).find('.teaser-image').html() == "") {
					$(this).find('.teaser-image').html(html);
					$(this).find('.teaser-image').show();
				}
			}).mouseout(function() {
				$(this).find('.results-preview').hide();
			});
		}
		$('h3.result-title a').each(function() {
				//var href = $(this).attr('href','/PdfViewerTags.aspx?img='+$(this).attr('id').toString()+'&firstvisit=true&src=search&currentResult=1');				
	    });
	    SetNewViewer();
	} else {
        // If there are no results...
        var SearchTerms = $get('lblSearchTerms'); 
        var SearchTerms2 = $get('lblSearchTerms2');
        // 12/29/2009 jao - added string replacement below
        SearchTerms.innerHTML = results.pSearchTerms.replace('!(!','(').replace('!)!',')');
        SearchTerms2.innerHTML = results.pSearchTerms.replace('!(!','(').replace('!)!',')');
        // G Davis, Sept 18, 2009 - adding references to the labels intended to
        // display the record range and the total number of records after 
        // the search is complete - in case nothing is found, both need to be set to 0 (zero)
        var CurrentContent = $get('lblCurrentViewingContent');
        var NumberOfNAResults = $get('lblNumberOfNAResults');
        CurrentContent.innerHTML = '0 ';
        NumberOfNAResults.innerHTML = '0 ';
          
        fcnShowHideSearching('noresults');
    } 
}

/*need*/
function OnWSRequestCompleteCustom(results)
{
    if(results.pNumberOfNAResults != "0")
    {
        var _pgindx=0;
        var arrindex = results.pCurrentContent.split("-");
        if(arrindex.length>0)
        {
            _pgindx=fcnGetArrayIndex(parseInt(arrindex[0]));
            _fetchedpageindex=_pgindx;   
        }
        if(StoreResult[_pgindx]==null)
        {
            StoreResult[_pgindx]=results;
        }
        else if(StoreResult.length>_pgindx)
        {
            StoreResult[_pgindx]=results;
        }
        else if(StoreResult.length<_pgindx)
        {
            var _xtraelements=_pgindx-StoreResult.length;
            for(var i=0; i<_xtraelements;i++)
            {
               if(StoreResult[i]=='undefined'){
                StoreResult[i]="";}
            }
            StoreResult[_pgindx]=results;
        }
     }
}
function OnWSRequestCompletePreviousFirst(results,_oSearch)
{
    if(results.pNumberOfNAResults != "0")
    {
        var _pgindx=0;
        var arrindex = results.pCurrentContent.split("-");
        if(arrindex.length>0)
        {
            _pgindx=fcnGetArrayIndex(parseInt(arrindex[0]));
            _startfetchedpageindex=_pgindx;   
        }
        if(StoreResult[_pgindx]==null)
        {
            StoreResult[_pgindx]=results;
        }
        else if(StoreResult.length>_pgindx)
        {
            StoreResult[_pgindx]=results;
        }
        else if(StoreResult.length<_pgindx)
        {
            var _xtraelements=_pgindx-StoreResult.length;
            for(var i=0; i<_xtraelements;i++)
            {
               if(StoreResult[i]=='undefined'){
                StoreResult[i]="";} 
            }
            StoreResult[_pgindx]=results;
        }
        fcnFirstPrevRequests(_oSearch); 
     }
}

function OnWSRequestCompleteFirst(results,oSearch)
{  
    if(results.pNumberOfNAResults != "0")
    {
        var _pgindx=0;
        var arrindex = results.pCurrentContent.split("-");
        if(arrindex.length>0)
        {
            _pgindx=fcnGetArrayIndex(parseInt(arrindex[0]));
            _fetchedpageindex=_pgindx;   
        }
        if(StoreResult[_pgindx]==null)
        {
            StoreResult[_pgindx]=results;
        }
        else if(StoreResult.length>_pgindx)
        {
            StoreResult[_pgindx]=results;
        }
        else if(StoreResult.length<_pgindx)
        {
            var _xtraelements=_pgindx-StoreResult.length;
            for(var i=0; i<_xtraelements;i++)
            {
               if(StoreResult[i]=='undefined'){
                StoreResult[i]="";} 
            }
            StoreResult[_pgindx]=results;
        }
        fcnFirstRequests(oSearch); 
     }
}
/* mod */
function fcnGetArrayIndex(arrindex)
{
    var index=0;
    if(arrindex!=0)
    {
        var elementInDropdown = parseInt($('#ctl00_ContentArea_SearchResultsControlV3_cboResultCount').val());
        index = (arrindex-1)/elementInDropdown;
    }
    return index;
}
function fcnGetArrayContentIndex(arrindex)
{
    var index=0;
    if(arrindex!=0)
    {
        var elementInDropdown = parseInt($('#ctl00_ContentArea_SearchResultsControlV3_cboResultCount').val());
        index = ((arrindex)/elementInDropdown);
    }
    return index;
}

function syncCheck(ctl) {
	var l = ctl.length;
	alert(ctl.slice(l-1, l));
}

function fcnChangeResultsPerPageCount(ctl) {
    var ctlVal = ctl.value;
	var syncElement = $get('ctl00_ContentArea_SearchResultsControlV3_cboResultCount2');
	void(syncElement.value = ctlVal);
	syncElement = $get('ctl00_ContentArea_SearchResultsControlV3_cboResultCount');
	void(syncElement.value = ctlVal);


	fcnShowSearchQuote();
	fcnShowHideSearching('searching');
	fcnUpdateResultsPerPage(ctl.value);     
	var oSearch = fcnGetValues();    
	oSearch.pResults = ctl.value;
	oSearch.pTotalSearchResults = '0';
	oSearch.pSearchEngineStartIndex = '0';
	oSearch.pPreviousSearch = 'false';
	StoreResult=new Array();
	_nofpageview=0;
	_noppageview=0;
    _currentpageindex=0;
    _fetchedpageindex=0;
	DoSearch(oSearch);
}

function fcnChangePageSortingOption(ctl, sync) {
    var ctlVal = ctl.value;
    var syncElement = $get('ctl00_ContentArea_SearchResultsControlV3_cboSortBy2');
	void(syncElement.value = ctlVal);
	syncElement = $get('ctl00_ContentArea_SearchResultsControlV3_cboSortBy');
	void(syncElement.value = ctlVal);
	
	fcnShowSearchQuote();
    fcnShowHideSearching('searching');
    fcnUpdateSortingOption(ctl.value); 
    var oSearch = fcnGetValues();
    oSearch.pSortBy = ctl.value;
    oSearch.pTotalSearchResults = '0';
    oSearch.pSearchEngineStartIndex = '0';
    oSearch.pPreviousSearch = 'false';
    StoreResult=new Array();
    _nofpageview=0;
    _currentpageindex=0;
    _fetchedpageindex=0;
	DoSearch(oSearch);  
}

function fcnUpdateResultsPerPage(value)
{
    var date = new Date();
    var today = new Date((date.getFullYear() + 1),date.getMonth(),date.getDate());	    
    document.cookie = ".newspaperarchive.com/ResultsPerPage=NumResults=" + value + "; expires=" + today.toUTCString() + "; path=/";
}  

function fcnUpdateSortingOption(value)
{
    var date = new Date();
    var today = new Date((date.getFullYear() + 1),date.getMonth(),date.getDate());	    
    document.cookie = ".newspaperarchive.com/SortingOption=sort=" + value + "; expires=" + today.toUTCString() + "; path=/";
}    
function GetReverseofPageIndex(PageIndex)
{
    var index = 0;
    if(parseInt(PageIndex)!=0)
    {
        var elementInDropdown = parseInt($('#ctl00_ContentArea_SearchResultsControlV3_cboResultCount').val());
        index = (PageIndex*elementInDropdown)+elementInDropdown;
    }
    return index;
}
function PageMove(page)
{
    var _selectedpageid=0;
    var _RevNo = 0;
    var NumberOfNAResults = $get('lblNumberOfNAResults');   
    var _curviewindex=parseInt($("#divNavTop span").html())-1;  
     
    if(_curviewindex<0){_curviewindex=0;}   
     
    if(page!='0'){
        _selectedpageid=fcnGetArrayContentIndex(parseInt(page));
    }
    else{
        _selectedpageid=0;
    }      
    if(_curviewindex>_selectedpageid)
    {
        _RevNo=GetReverseofPageIndex(_startfetchedpageindex);
    }
    else{
        _RevNo=GetReverseofPageIndex(_fetchedpageindex);
    } 
    
    if(StoreResult[_selectedpageid]!=null)
    {
        fcnGetArrayResult(StoreResult[_selectedpageid]);
        
        if(NumberOfNAResults != null)
        { 
            var sNumber = NumberOfNAResults.innerHTML.trim().replace(',','');
            for(x=0;x<3;x++)
            {
                sNumber = sNumber.replace(',','')
            }
            var ocSearch = fcnGetValues();        
            ocSearch.pTotalSearchResults = sNumber;
            ocSearch.pSearchEngineStartIndex = _RevNo.toString();
            ocSearch.pPreviousSearch = 'False';
            fcnCustomRequests(ocSearch);
        }
    }
    else
    {  
        fcnShowSearchQuote();
        fcnShowHideSearching('searching');       
        if(NumberOfNAResults != null)
        { 
            var sNumber = NumberOfNAResults.innerHTML.trim().replace(',','');
            for(x=0;x<3;x++)
            {
                sNumber = sNumber.replace(',','')
            }
            var oSearch = fcnGetValues();        
            oSearch.pTotalSearchResults = sNumber;
            oSearch.pSearchEngineStartIndex = page;
            oSearch.pPreviousSearch = 'False';
            runSearch(oSearch);
            
            oSearch.pSearchEngineStartIndex = (parseInt(page))+parseInt($('#ctl00_ContentArea_SearchResultsControlV3_cboResultCount').val());
            fcnCustomRequests(oSearch);
        }
    }
    window.scrollTo(0,0);
}


function fcnGetSearchTerms(oSearch)
{
    var SearchTermsID = $get('hdnSearchTermsId');
    if(SearchTermsID != null)
    { 
        if(SearchTermsID.value != "")
        {
            var SearchTerms = $get(SearchTermsID.value);
            if(SearchTerms != null)
            {               
                var sTerms = '';
                sTerms = BuildTerms(oSearch.pAllWords, sTerms, ' AND ', '', '');
                if((oSearch.pFirstName != '') && (oSearch.pLastName != ''))
                {
                    sTerms += oSearch.pFirstName + ' ' + oSearch.pLastName;
                }
                if(oSearch.pExactPhrase != '')
                {
                    if(sTerms == '')
                        sTerms += '\"' + oSearch.pExactPhrase + '\" ';
                    else
                        sTerms += ' AND \"' + oSearch.pExactPhrase + '\" ';
                }
                sTerms += BuildTerms(oSearch.pLeastOneWord, sTerms, ' OR ', '(', ')');
                sTerms += BuildTerms(oSearch.pWithoutWord, sTerms, ' AND NOT ', ' NOT ', '');
                sTerms += BuildLocationTerms(oSearch);
                sTerms += BuildDateTerms(oSearch);
                SearchTerms.innerHTML = sTerms;
                fcnShowSearchQuote();
                fcnShowHideSearching('searching');
            }  
        } 
    } 
}

function fcnShowSearchQuote()
{    
    var blnFound = false;    
    var TestQuote = $get('divSearchQuote2');    
    if(TestQuote != null)
    {
        for(x=1;x<11;x++)
        {
            var SearchQuote = $get('divSearchQuote' + x);
            if(SearchQuote != null)
            {
                if(SearchQuote.className == 'rotating_bits')
                {
                    SearchQuote.className = 'rotating_bits hidden';
                    blnFound = true;
                    if(x == 10)
                    {
                        var FirstSearchQuote = $get('divSearchQuote1');
                        if(FirstSearchQuote != null)
                        {
                            FirstSearchQuote.className = 'rotating_bits';
                        }
                    }
                }
                else if(blnFound)
                {
                    SearchQuote.className = 'rotating_bits';
                    blnFound = false;
                }
                else
                {
                    SearchQuote.className = 'rotating_bits hidden';
                }
            }
        }
    }    
}

function BuildLocationTerms(oSearch)
{
    var sTerms = '';
    
    if(oSearch.pTitleName != 'All' && oSearch.pTitleName != '')
    {
        sTerms += ' In '+ oSearch.pTitleName;
    }
    else if(oSearch.pStateName != 'All' && oSearch.pStateName != '')
    {
        sTerms += ' In '+ oSearch.pStateName;
        if(oSearch.pCityName != 'All' && oSearch.pCityName != '')
            sTerms += ', '+ oSearch.pCityName;
    }

    return sTerms;
}


function BuildDateTerms(oSearch)
{
    var sTerms = '';
    var sBMonthName = '';
    
    if(oSearch.pBeginMonthName != 'Month' && oSearch.pBeginMonthName != '')
        sBMonthName = oSearch.pBeginMonthName;
    else if(oSearch.pMonthName != 'Month' && oSearch.pMonthName != '')
        sBMonthName = oSearch.pMonthName;

    if(oSearch.pYear != '' && oSearch.pMonth != '' && oSearch.pDay != '')
    {
        if(oSearch.pEndYear != '' && oSearch.pEndMonth != '' && oSearch.pEndDay != '')
        {
            sTerms += ' AND From ' + sBMonthName + ' ' + oSearch.pDay + ', ' + oSearch.pYear;
            sTerms += ' to ' + oSearch.pEndMonthName + ' ' + oSearch.pEndDay + ', ' + oSearch.pEndYear;
        }    
        else
            if(oSearch.pEndYear != '')
                sTerms += ' AND Between ' + oSearch.pYear + ' AND ' + oSearch.pEndYear + ' AND In ' + sBMonthName + ' AND Day:' + oSearch.pDay;
            else
                sTerms += ' AND On ' + sBMonthName + ' ' + oSearch.pDay + ', ' + oSearch.pYear;
    }
    else if(oSearch.pYear != '')
    {
        if(oSearch.pEndYear != '')
        {
            sTerms += ' AND From ' + oSearch.pYear + ' to ' + oSearch.pEndYear;
            if(oSearch.pMonth != '')
                sTerms += ' AND In ' + sBMonthName;
        }
        else
        {
            if(oSearch.pMonth != '')
                sTerms += ' AND Year:' + oSearch.pYear + ' AND In ' + sBMonthName;
            else
                sTerms += ' AND Year:' + oSearch.pYear;
        }
    }
    else if(sBMonthName != '')
    {
        sTerms += ' AND Month:' + sBMonthName;
        if(oSearch.pDay != '')
            sTerms += ' AND Day:' + oSearch.pDay;
    }
    else if(oSearch.pDay != '')
    {
        sTerms += ' AND Day:' + oSearch.pDay;
    }
    
    return sTerms;
}

function BuildTerms(sValue, sTemp, sKey, sStart, sEnd)
{
    var sTerms = '';
    
    if(sValue != '')
    {        
        var aValues = new Array();
        aValues = sValue.split(' ');
        
        if(aValues.length > 1)
        {
            for (x in aValues)
            {
                if(aValues[x].toString().toUpperCase() != 'AND' && aValues[x].toString().toUpperCase() != 'OR' && aValues[x].toString().toUpperCase() != 'NOT')
                {
                    if(x == 0)
                    {
                        if(sTemp == '')
                            sTerms = sStart + aValues[x].toString() + sKey;
                        else
                            sTerms = ' AND ' + sStart + aValues[x].toString() + sKey;
                    }
                    else if(x < aValues.length - 1)
                    {
                        sTerms += aValues[x].toString() + sKey;
                    }
                    else
                    {
                        sTerms += aValues[x].toString() + sEnd;
                    }
                }
            }
        }
        else
        {
            if(sTemp != '')
                sTerms = ' AND ' + sStart + sValue + sEnd;
            else
                sTerms = sStart + sValue + sEnd;
        }
    }
    return sTerms;
}


function objSearch()
{
    this.pCountryID = '';
    this.pStateID = '';
    this.pCityID = '';
    this.pTitleID = '';
    this.pAllWords = '';
    this.pSearchBoxSearch = '';
    this.pExactPhrase = '';
    this.pLeastOneWord = '';
    this.pWithoutWord = '';
    this.pYear = '';
    this.pMonth = '';
    this.pDay = '';
    this.pEndYear = '';
    this.pEndMonth = '';
    this.pEndDay = '';
    this.pResults = '';
    this.pTotalSearchResults = '';
    this.pSearchEngineStartIndex = '';
    this.pSortBy = '';    
    this.pAdditionalTerms = '';
    this.pNewContent = '';
    this.pPreviousSearch = '';    
    this.pCountryName = '';
    this.pStateName = '';
    this.pCityName = '';
    this.pTitleName = '';
    this.pBeginMonthName = '';
    this.pEndMonthName = '';
    this.pMonthName = '';
    this.pFrontPage = '';
    this.GetDateValues = GetDateValues;
}

function GetDateValues(oControlNames)
{        
    var BeginYear = $get(oControlNames.pBDates + 'cboBeginYear').value;
    var BeginMonth = $get(oControlNames.pBDates + 'cboBeginMonth').value;
    var BeginDay = $get(oControlNames.pBDates + 'cboBeginDay').value;
    var EndYear = $get(oControlNames.pBDates + 'cboEndYear').value;
    var EndMonth = $get(oControlNames.pBDates + 'cboEndMonth').value;
    var EndDay = $get(oControlNames.pBDates + 'cboEndDay').value;
    var BetweenBeginYear = $get(oControlNames.pBYears + 'cboBetweenBeginYear').value;
    var BetweenEndYear = $get(oControlNames.pBYears + 'cboBetweenEndYear').value;
    var ExactYear = $get(oControlNames.pEDate + 'cboExactYear').value;
    var ExactMonth = $get(oControlNames.pEDate + 'cboExactMonth').value;
    var ExactDay = $get(oControlNames.pEDate + 'cboExactDay').value;
    
    if(BeginYear != 0)
        this.pYear = BeginYear;
    else if(BetweenBeginYear != 0)
        this.pYear = BetweenBeginYear;
    else if(ExactYear != 0)
        this.pYear = ExactYear;
        
    if(BeginMonth != 0)
        this.pMonth = BeginMonth;
    else if(ExactMonth != 0)
        this.pMonth = ExactMonth;

    if(BeginDay != 0)
        this.pDay = BeginDay;
    else if(ExactDay != 0)
        this.pDay = ExactDay;       
        
    if(EndYear != 0)
        this.pEndYear = EndYear;
    else if(BetweenEndYear != 0)
        this.pEndYear = BetweenEndYear;          
        
    if(EndMonth != 0)
        this.pEndMonth = EndMonth;
    
    if(EndDay != 0)
        this.pEndDay = EndDay;                
}

function objControlNames()
{    
    this.pBYears = '';
    this.pBDates = '';
    this.pEDate = '';
    this.pSearchTerms = '';
}

function SetNewViewer() {
    $('a.result-link').removeAttr("onclick");
    $('a.result-link').click(function(event) {
	    if ($('#class_wrap').hasClass('anonymous')) {setURL(); return false;  }
	        if(username==null || username=="") {
	            event.preventDefault();	  
	            $('#flaviewer').attr('href',this.toString().replace('PdfViewerTags','NewPdfViewer'));
	            $('#pdfviewer').attr('href',this.toString());   
	            if (!$('#class_wrap').hasClass('anonymous')){
	            $.colorbox({inline:true, width:450, heigh:350, href:"#divSelect"});}
                return false;
            }
            else {
                if (username=="flaviewer") {
	                $('a.result-link').attr('href',this.toString().replace('PdfViewerTags','NewPdfViewer')); }
            }	
            return true;   	    
	 });	 
	if(username==null && username=="" && username=="undefined"){
      $('a.result-link').each(function() {	
            $('<span>&nbsp;</span><a class="setting" onclick="return vsettings(\''+this.toString()+'\');">Change Viewer</a>').insertAfter($(this));
        });
    }
	if (username=="flaviewer") {        
        $('a.result-link').each(function() {				
		    var hrefc = $(this).attr('href').toString();	
		    $(this).attr("href",hrefc.replace('PdfViewerTags','NewPdfViewer'));
		    $('<span>&nbsp;</span><a class="setting" onclick="return vsettings(\''+this.toString()+'\');">Change Viewer</a>').insertAfter($(this));
	    });
     }
     else if (username=="pdfviewer") {
        $('a.result-link').each(function(){	
            $('<span>&nbsp;</span><a class="setting" onclick="return vsettings(\''+this.toString()+'\');">Change Viewer</a>').insertAfter($(this));
        });
     }
}
function setURL(){
    if(lockdown=='lockdown'){ displayPopup(); $('.ui-dialog-titlebar-close').css('display','none');} else { document.location = '/register/premium.aspx'; }
}

//For Save Results in SearchResultsV3 page  *******20111104*******
function fcnSaveSelectedResults(strSearch,ctl,doCallback)
{var arSelected=document.getElementsByName('addResult');var strAddItems='';strAddItems+='Search:'+strSearch+'%7CList:';var blnHasSelected=false;for(var intCount=0;intCount<arSelected.length;intCount++)
{if(arSelected[intCount].checked)
{strAddItems+=arSelected[intCount].id+'+';blnHasSelected=true;}}
if(blnHasSelected)
{doCallback(ctl,strAddItems,fcnInvokeScript,'');}
else
{window.alert('You must select a result to save.');}
strAddItems=null;arSelected=null;}
function fcnInvokeScript(strScript)
{var fcnDo=new Function(strScript);return fcnDo();}
