var smssearch2Startpos = 0;//is set to startpos of the search upon loading the page
var smssearch2Maxrows = 0;//is set to the maxrows upon loading the page
var smssearch2thdir = 'TH170';//keeps track of thdir
var smssearch2NoPaginatorlinks = 0;//is loaded with the number of paginator links in the page upon loading
var smssearch2ProcessPaginator = 1;//if set to 0, paginator links, number of results etc are not set.
var smssearch2Debugmode = 0;
var smssearch2showEmptyOnZeroresults = 0;//if set to 1, component 'EmptysearchImage' is made visible if 0 zero results are found

var smssearch2totimgcount = 0;
var smssearch2SearchIsPending = 0;

var smssearch2ProcessSearchProfiles = 0;
var smsSearch2ProfileAmountsSet = 0;
var isSequentialCall = 0;//this is set to one upon a paginator click, to force page 1 to be displayed instead of remembering the last known position

var calledWithFrame = 0;//is 1, the top-window will scroll to top upon a pagechange. 

//=============================================== XML COMMUNICATION FUNCTIONS ======================================================================================
//function to do the actual calls to the scripts to get the search results
function smsSearch2Init(){
	thefrm = document.getElementById("smsSearch2srcform");
	thefrm.startrowZerobased.value = smssearch2Startpos;
	thefrm.maxrows.value = smssearch2Maxrows;
	thefrm.thdir.value = smssearch2thdir;
	thefrm.forceFirstPos.value = isSequentialCall;
	
	if(smssearch2totimgcount!=0){//sequential call to the search, scroll the page to the top
		self.scrollTo(0, 0);
	}
	
	smssearch2SearchIsPending=1;
	errsrccnt = window.setTimeout('errsrc()', 90000);
	
	//alert('init, setURLhashpos('+smssearch2Startpos+')')
	setURLhashpos(smssearch2Startpos);
	
	thediv = document.getElementById("search_emptysearchimage_I_image");
	if(thediv!=null) thediv.style.display = 'none';
	
	//document.getElementById("debugmsg").innerHTML = 'firing submit to hidden frame';
	thefrm.submit();
	
	isSequentialCall = 1;
}

//function to display results: receive the HTML content and to set further display items (paginator etc)
function smsSearch2Setresdata(htmlres, setPos){
	//document.getElementById("debugmsg").innerHTML = 'reddata received with smssearch2SearchIsPending='+smssearch2SearchIsPending;
	
	if(smssearch2SearchIsPending==1){
		window.clearTimeout(errsrccnt);
		
		smssearch2Startpos=setPos;
		
		tgtdiv = document.getElementById("searchresults_C_imagecontainer");
		tgtdiv.innerHTML = htmlres;
		tgtdiv.style.display = 'block';
		
		divsearchrescounterTotNoImages = document.getElementById("searchrescounterTotNoImages");
		smssearch2totimgcount = parseInt(divsearchrescounterTotNoImages.innerHTML);
		
		divsearchrescounterDispNoImages = document.getElementById("searchrescounterDispNoImages");
		noImages = parseInt(divsearchrescounterDispNoImages.innerHTML);
		
		smssearch2SearchIsPending=0;
		
		smsSearch2FinishDisplay(noImages);
		rememberStartpos();
		
		//if you need a custom function to run after the search finishes, make a function 'runAfterSearchFinish' and it will be called automatically with resultcount and startpos
		if((typeof runAfterSearchFinish != 'undefined') && (typeof runAfterSearchFinish == 'function')){
			runAfterSearchFinish(smssearch2totimgcount, smssearch2Startpos);
		}
	}
}

//alternative function for displaying results: html content is put in serverside. Only set further display items (paginator etc)
var smsSearch2SetresServerdataprocessed=0;
function smsSearch2SetresServerdata(setPos){
	//document.getElementById("debugmsg").innerHTML = 'reddataserver received with isSequentialCall='+isSequentialCall;
	if(isSequentialCall==0){//due to automatic reload after a goback to search for other than page 1, this function may be called after smsSearch2Setresdata of the reload. therefore block if a sequential call is made already
		smssearch2Startpos=setPos;
		
		divsearchrescounterTotNoImages = document.getElementById("searchrescounterTotNoImages");
		smssearch2totimgcount = parseInt(divsearchrescounterTotNoImages.innerHTML);
		
		divsearchrescounterDispNoImages = document.getElementById("searchrescounterDispNoImages");
		noImages = parseInt(divsearchrescounterDispNoImages.innerHTML);
		
		smssearch2SearchIsPending=0;
		smsSearch2FinishDisplay(noImages);
		
		if(verifyposToHash(setPos)!=true){
			if(smsSearch2SetresServerdataprocessed==0){
				hashpos = getHashpos();
				smsSearch2GotoPage(hashpos);
			}
		}
		else{
			//if you need a custom function to run after the search finishes, make a function 'runAfterSearchFinish' and it will be called automatically with resultcount and startpos
			if((typeof runAfterSearchFinish != 'undefined') && (typeof runAfterSearchFinish == 'function')){
				runAfterSearchFinish(smssearch2totimgcount, smssearch2Startpos);
			}
		}
	}
}

function smsSearch2CheckDisplayPosition(){//this checks to makes sure that after user clicks browser-BACK, the latest shown page is displayed
	storeform = document.getElementById("smsSearch2storeform");
	storeform.startpos.value = eval(smssearch2Startpos+1);
	storeform.chkaction.value = 'checkpos';
	//storeform.submit();
}

//function to clear search if it takes more than 60 seconds
function errsrc(){
	if(smssearch2SearchIsPending==1){
		tgtdiv = document.getElementById("searchresults_C_imagecontainer");
		tgtdiv.innerHTML = '<table width="100%"><tr><td align="center">An error has occurred during the search. Please try again.</td></tr></table>';
		tgtdiv.style.display = 'block';
		smssearch2totimgcount=0;
		noImages=0;
		smssearch2SearchIsPending=0;
		smsSearch2FinishDisplay(0);
	}
}

function rememberStartpos(){
	if(smssearch2Debugmode==0 && smssearch2ProcessPaginator!=0){//if debugmode==1, then iframe with searchresults and errors is visible. Do not overwrite this content. if smssearch2ProcessPaginator==0, similar image search, do not store session details
		storeform = document.getElementById("smsSearch2storeform");
		storeform.startpos.value = eval(smssearch2Startpos+1);
		storeform.maxrows.value = smssearch2Maxrows;
		storeform.thdir.value = smssearch2thdir;
		//storeform.submit();
	}
}

//function to set the final presentation of results after last result pos is set: set paginator and total number of results
function smsSearch2FinishDisplay(noImages){
	//hide loading image and positioning div
	loadingdiv = document.getElementById("smssearch2resLoadingimg");
	if(loadingdiv!=null) loadingdiv.style.display = 'none';
	
	//set total number of results
	if(smssearch2ProcessPaginator!=0){
		thediv = document.getElementById("searchresultHead_L_numberOfresults");
		if(thediv!=null) thediv.innerHTML = smssearch2totimgcount;
		thediv = document.getElementById("searchresultHead_L_numberOfresults2");
		if(thediv!=null) thediv.innerHTML = smssearch2totimgcount;
	}
	
	//bug in IE7, somehow not all images get display=block always. Therefore make sure that it's set again at the end of the call
	for(x=0; x<noImages; x++){
		screenpos = x+1;
		document.getElementById("searchresults_image_"+screenpos).style.display = 'block';		
	}
	
	//show/hide paginator items
	smsSearch2DispPaginator();
		
	//show Empty search image if needed
	if(smssearch2showEmptyOnZeroresults==1 && smssearch2totimgcount==0){
		thediv = document.getElementById("search_emptysearchimage_I_image");
		if(thediv!=null) thediv.style.display = 'block';

		srcfrmdisp = document.getElementById("smsSearch2fr").style.display;
		searchdiv = document.getElementById("searchresults_C_imagecontainer");

		if(srcfrmdisp==null && searchdiv!=null) {searchdiv.style.display = 'none';}
		else if(srcfrmdisp=='block') {}//search frame is in debug mode, do not hide it
		else if(searchdiv!=null) {searchdiv.style.display = 'none';}
	}
	else if(smssearch2showEmptyOnZeroresults==1){//if results are found, enforce hiding empty search and show results. 
		thediv = document.getElementById("search_emptysearchimage_I_image");
		if(thediv!=null) thediv.style.display = 'none';

		searchdiv = document.getElementById("CI_search_searchresults");
		if(searchdiv!=null) searchdiv.style.display = 'block';
	}
		
	//if used, show profile filter number of results
	smsSearch2LoadProfileAmounts();
	
	//load javascript after ajax results
	if(typeof(ajaxready)=='function'){
		ajaxready();
	}
	
	//load javascript after ajax results
	if(typeof(loadaftersearch)=='function'){
		loadaftersearch();
	}
}

function smsSearch2DispPaginator(){
	if(smssearch2ProcessPaginator==0)
		return;
		
	//show all needed paginator links
	totalCount = smssearch2totimgcount;
	currStartpos = smssearch2Startpos+1;//zero based startpos + 1
	currEndpos = parseInt(smssearch2Startpos) + parseInt(smssearch2Maxrows);
	
	if(currEndpos>totalCount){
		currEndpos = totalCount;
	}
	
	noLinks = Math.ceil(totalCount / smssearch2Maxrows);
	
	if(noLinks<2){
		thediv = document.getElementById("searchresultspaginator_F_pageinfo");
		if(thediv!=null) thediv.style.display = 'none';
		thediv = document.getElementById("searchresultspaginator_F2_pageinfo");
		if(thediv!=null) thediv.style.display = 'none';
		return;
	}
	currPage = Math.ceil(smssearch2Startpos / smssearch2Maxrows)+1;
	if(noLinks<=smssearch2NoPaginatorlinks){//if the total number of links LTE the maximum number to display, always start at position 1
		firstLinkpos = 1;
	}
	else{//If the search results cause for more links than the max number of links to display, check for the first link that should be displayed
		firstLinkpos = currPage - Math.floor(smssearch2NoPaginatorlinks/2);
		if(firstLinkpos>noLinks-smssearch2NoPaginatorlinks+1){
			firstLinkpos=noLinks-smssearch2NoPaginatorlinks+1
		}
		if(firstLinkpos<1){
			firstLinkpos = 1;
		}
	}
	
	//alert('Going to set page numbers.\nfirstLinkpos='+firstLinkpos+'\ncurrPage='+currPage+'\nnoLinks='+noLinks+'\ntotalCount='+totalCount+'\ncurrStartpos='+currStartpos+'\ncurrEndpos='+currEndpos+'\ntotalCount='+totalCount+'\nsmssearch2Maxrows='+smssearch2Maxrows);
	
	maxlink = noLinks-firstLinkpos+1;
	
	//handle paginator on top of page
	for(x=1; x<=smssearch2NoPaginatorlinks; x++){
		l = document.getElementById("searchresultspaginator_F_pagelink_"+x);
		d = document.getElementById("searchresultspaginator_C_pagelink_"+x);
		if(l!=null){
			if(x<=maxlink){
				linknr = x + firstLinkpos - 1;
				d.style.display = 'block';
				l.innerHTML = linknr;
				l.title = linknr;
				l.href = "javascript:smsSearch2PageLink("+parseInt(x + firstLinkpos - 1)+")";
				if(linknr==currPage){
					l.style.fontWeight = 'bold';
					l.className = 'searchresultspaginator_activeNav';
				}else{
					l.style.fontWeight = 'normal';
					l.className = 'searchresultspaginator_normalNav';
				}
			}
			else{
				d.style.display = 'none';
			}
		}
	}
	divPrevButt = document.getElementById("searchresultspaginator_F_prevcontainer");
	if(divPrevButt!=null) divPrevButt.style.display = (smssearch2Startpos==0)?'none':'block';
	divNextButt = document.getElementById("searchresultspaginator_F_nextcontainer");
	if(divNextButt!=null) divNextButt.style.display = (totalCount<=currEndpos)?'none':'block';
	divPagFrm = document.getElementById("searchresultspaginator_F_pagefrmcontainer");
	if(divPagFrm!=null) divPagFrm.style.display = 'block';
	thediv = document.getElementById("searchresultspaginator_F_pageinfo");
	if(thediv!=null) thediv.style.display = 'block';
	thediv = document.getElementById("searchresultspaginator_F_currpage");
	if(thediv!=null) thediv.innerHTML = Math.round(((smssearch2Startpos-1) / smssearch2Maxrows) + 1);
	thediv = document.getElementById("searchresultspaginator_F_totpages");
	if(thediv!=null) thediv.innerHTML = Math.ceil(smssearch2totimgcount / smssearch2Maxrows);
	
	//handle paginator in bottom of page
	for(x=1; x<=smssearch2NoPaginatorlinks; x++){
		l = document.getElementById("searchresultspaginator_F2_pagelink_"+x);
		d = document.getElementById("searchresultspaginator_C2_pagelink_"+x);
		if(l!=null){
			if(x<=noLinks){
				linknr = x + firstLinkpos - 1;
				d.style.display = 'block';
				l.innerHTML = linknr;
				l.href = "javascript:smsSearch2PageLink("+parseInt(x + firstLinkpos - 1)+")";
				if(linknr==currPage){
					l.style.fontWeight = 'bold';
					l.className = 'searchresultspaginator_activeNav';
				}else{
					l.style.fontWeight = 'normal';
					l.className = 'searchresultspaginator_normalNav';
				}
			}
			else{
				d.style.display = 'none';
			}
		}
	}
	divPrevButt = document.getElementById("searchresultspaginator_F2_prevcontainer");
	if(divPrevButt!=null) divPrevButt.style.display = (smssearch2Startpos==0)?'none':'block';
	divNextButt = document.getElementById("searchresultspaginator_F2_nextcontainer");
	if(divNextButt!=null) divNextButt.style.display = (totalCount<=currEndpos)?'none':'block';
	divPagFrm = document.getElementById("searchresultspaginator_F2_pagefrmcontainer");
	if(divPagFrm!=null) divPagFrm.style.display = 'block';
	thediv = document.getElementById("searchresultspaginator_F2_pageinfo");
	if(thediv!=null) thediv.style.display = 'block';
	thediv = document.getElementById("searchresultspaginator_F2_currpage");
	if(thediv!=null) thediv.innerHTML = Math.round(((smssearch2Startpos-1) / smssearch2Maxrows) + 1);
	thediv = document.getElementById("searchresultspaginator_F2_totpages");
	if(thediv!=null) thediv.innerHTML = Math.ceil(smssearch2totimgcount / smssearch2Maxrows);
	
	thediv = document.getElementById("searchresultspaginator_F_GoToPage_container");
	if(thediv!=null) $("#searchresultspaginator_F_GoToPage_container").show();
	
	thediv = document.getElementById("searchresultspaginator_F2_GoToPage_container");
	if(thediv!=null) $("#searchresultspaginator_F2_GoToPage_container").show();
	
	thediv = document.getElementById("searchresultspaginator_F_navigation");
	if(thediv!=null) $("#searchresultspaginator_F_navigation").show();
	
	thediv = document.getElementById("CI_search_searchresultPaginator");
	if(thediv!=null) $("#CI_search_searchresultPaginator").show();
	
	thediv = document.getElementById("CI_search_searchresultPaginator2");
	if(thediv!=null) $("#CI_search_searchresultPaginator2").show();
}

function smsSearch2LoadProfileAmounts(){
	//Load amounts of results per profile if needed
	if(smsSearch2ProfileAmountsSet==0 && smssearch2ProcessSearchProfiles==1 && smssearch2totimgcount!=0){
		smsSearch2ProfileAmountsSet = 1;
		thefrm = document.getElementById("smsSearch2srcform");
		thefrm.elements.action.value = 'loadSeachProfileAmounts';
		thefrm.submit();
		thefrm.elements.action.value = 'doSearch';
	}
	
	//if profiles were used in this search results, make sure to highlight used profiles, also when clicking back 
	if(smssearch2ProcessSearchProfiles==1){
		profdiv = document.getElementById("searchresUsedProfileFilter");
		allprofsdiv = document.getElementById("searchProfile_catlist");
		if(profdiv!=null && allprofsdiv!=null){
			usedProfs = profdiv.innerHTML;
			allProfs = allprofsdiv.innerHTML;
			if(usedProfs!=''){
				usedProfs_a = usedProfs.split(',');
				allProfs_a = allProfs.split(',');
				for(uidx=0; uidx<usedProfs_a.length; uidx++){
					curProfid = usedProfs_a[uidx];
					for(pidx=0; pidx<allProfs_a.length; pidx++){
						proftag = allProfs_a[pidx].split('_');
						profgroup = proftag[0];
						profid = proftag[1];
						if(profid==curProfid){
							//current category should be highlighted: open the group and mark this one as active and the any-category of this group as inactive
							groupdiv = $('#searchProfile_G_'+profgroup);
							itemdiv = $('#searchProfile_items_'+profgroup);
							
							isOpen = groupdiv.hasClass('searchProfile_G_open');
							if(!isOpen){
								groupdiv.removeClass('searchProfile_G_close');
								groupdiv.addClass('searchProfile_G_open');
								itemdiv.slideDown('slow');
							}		
							
							setSearchProfile(parseInt(profgroup), parseInt(profid), 1);
						}
					}
				}
			}
		}
	}
}

function smsSearch2SetProfileAmounts(profileAmounts){
	profile_a = profileAmounts.split(',');
	for(p=0; p<profile_a.length; p++){
		profdetails_a = profile_a[p].split(':');
		if(profdetails_a.length==2){
			profileid = profdetails_a[0];
			profileAmount = profdetails_a[1];
			tgtdiv = document.getElementById("searchProfileItem_counter_"+profileid);
			if(tgtdiv!=null){
				tgtdiv.innerHTML = '(' + profileAmount + ')';
			}
		}
	}
		
	thefrm = document.getElementById("smsSearch2srcform");
	thefrm.profileFiltersSet.value=1;
}

//function to clear the pagecontent upon page navigation
function smsSearch2ClearDisplay(){
	for(x=0; x<smssearch2Maxrows; x++){
		screenpos = x+1;
		tgtResdiv = document.getElementById("searchresults_image_"+screenpos);
		if(tgtResdiv!=null) tgtResdiv.style.display = 'none';
	}
	
	tgtdiv = document.getElementById("searchresults_C_imagecontainer");
	tgtdiv.style.display = 'none';

	loadingdiv = document.getElementById("smssearch2resLoadingimg");
	if(loadingdiv!=null) loadingdiv.style.display = 'block';
}

//for back-button use, make sure that the url of the page is set with startpos in a hash. For this, there must be an actual link with that name otherwise IE will not do it
function setURLhashpos(pos){
	winloc = window.location.href;
	if(winloc.indexOf('#')!=-1){
		winloc = winloc.substring(0, winloc.indexOf('#'));
	}
	document.getElementById("paginatorhashanch").setAttribute("name","s"+pos);
	window.location.href = winloc + '#s' + pos;
}
function verifyposToHash(pos){
	hashVal = getHashpos();
	//alert('verifyposToHash, hashVal='+hashVal+', pos='+pos);
	if(hashVal==pos)
		return true;
	else
		return false;
}
function getHashpos(){
	hashVal = 0;
	if(window.location.href.indexOf('#')!=-1){
		hashVal = window.location.href.substring(window.location.href.indexOf('#')+2);
	}
	return hashVal;
}

//=============================================== PAGE NAVIGATION FUNCTIONS =========================================================================================

//function called by clicking a page number from the paginator
function smsSearch2PageLink(pageNum){

	thepos = parseInt((pageNum-1) * smssearch2Maxrows);
	if ( document.getElementById("newpageid")!= null ){
		document.getElementById("newpageid").value=	thepos;
		document.getElementById("safariform").submit();	
	}
	smsSearch2GotoPage(thepos);
}

//function to go to a particular page from submitting the gotopage-form in the paginator
function smsSearch2PageGoto(frmname){
	srcForm = document.getElementById(frmname);
	maxRows = smssearch2Maxrows;
	
	pagNum = srcForm.pagenum.value;
	if(pagNum!='' && pagNum > 0){
		thePos = (parseInt(pagNum)-1) * parseInt(maxRows) + 1;
		smsSearch2GotoPage(thePos);
	}
}

//function fired by click on previous buttons
function smsSearch2GoPrevious(){
	thepos = parseInt(smssearch2Startpos) - parseInt(smssearch2Maxrows);
	smsSearch2GotoPage(thepos);
}

//function fired by click on next button
function smsSearch2GoNext(){
	thepos = parseInt(smssearch2Startpos) + parseInt(smssearch2Maxrows);
	smsSearch2GotoPage(thepos);
}	

//the function that finally initiates the move to another page of the result
function smsSearch2GotoPage(offset){
	if(smssearch2totimgcount>=offset && offset>=0){
		//remember that paginator has been used
		isSequentialCall = 1;
		
		//set the starting pos
		smssearch2Startpos = offset;
	
		//clear currently displayed images
		smsSearch2ClearDisplay();
		
		//renew search results
		smsSearch2Init();
	}
}

//function to change the number of maxrows without reloading the entire page
function smsSearch2SetMaxRows(maxrows){
	smsSearch2ClearDisplay();
	smssearch2Maxrows = maxrows;
	smssearch2Startpos = 0;
	isSequentialCall = 1;
	smsSearch2Init();
}

//function to change the thumbnail size
function smsSearch2SetThdir(thdir){
	smsSearch2ClearDisplay();
	smssearch2thdir = thdir;
	smsSearch2Init();
}

//========================= search filter profile scripting ================================
$(document).ready(function(){
	$(".searchProfile_title").click(function(){
		thedivid = $(this).attr('id');
		itemid_a = thedivid.split('_')
		itemid = itemid_a[itemid_a.length-1];
		groupdiv = $('#searchProfile_G_'+itemid);
		itemdiv = $('#searchProfile_items_'+itemid);
		
		isOpen = groupdiv.hasClass('searchProfile_G_open');
		if(isOpen){
			itemdiv.slideUp('slow', function(){
				groupdiv.removeClass('searchProfile_G_open');
				groupdiv.addClass('searchProfile_G_close');			
			});
		}
		else{
			groupdiv.removeClass('searchProfile_G_close');
			groupdiv.addClass('searchProfile_G_open');
			itemdiv.slideDown('slow');
		}		
	});
})

var searchProfileVals = new Object();
function setSearchProfile(catid, profileid, preventLoad){
	if(searchProfileVals['cat_'+catid] == null || searchProfileVals['cat_'+catid] == 0){//currently no value is set for this category
		curprof = 0;
	}
	else{
		curprof = searchProfileVals['cat_'+catid];
	}
	
	searchProfileVals['cat_'+catid] = profileid;
	$('#searchProfileItem_'+catid+'_'+curprof+' A').removeClass('searchProfileSelected')
	$('#searchProfileItem_'+catid+'_'+profileid+' A').addClass('searchProfileSelected')
	
	searchProfilesEncoded='';
	for(x in searchProfileVals){
		if(searchProfileVals[x]!=0){
			if(searchProfilesEncoded==''){
				searchProfilesEncoded = searchProfileVals[x];
			}
			else{
				searchProfilesEncoded = searchProfilesEncoded + ',' + searchProfileVals[x];
			}
		}
	}
	
	thefrm = document.getElementById("smsSearch2srcform");
	thefrm.searchProfileFilters.value = searchProfilesEncoded;
	
	//Reload search
	if(preventLoad==null)
		smsSearch2GotoPage(0)
}

//var to state that this script is loaded, so that the init function can be called
smssearch2isReady = 1;

function dump(s){
	str='dump\n';
	cnt=0;
	for(X in s){
		str += 'str.'+X+' is '+s[X]+' \n';
		cnt++
		if(cnt==50){
			alert(str);
			cnt=0;
			str='dump\n';
		}
	}
	alert(str);
}
