//AjaxSearch.js
//Created by: KyleJ (kjaebker@muddydogpaws.com)
//Created on: 03/14/06
//Description: This code is used to setup the ajax search request.
//My thanks to Steve Smith of orderlist.com for sharing his code on how he did this
//Live Search by Thomas (Shadock)

//Updated: 06/03/07 - Added utf8 fix from atma
//Updated: 01/22/07 - Switched to mootools support
//Updated: 09/18/06 - Added user permissions to searching

//set the loading image to the correct location for you
//set the close image to the correct location for you
//set the ajax call to the correct location of ajaxSearch.php

//From Thomas : vars for live search
var _oldInputFieldValue="";
var _currentInputFieldValue="";
var _timeoutAdjustment=0;
var newToggle;
var is_searching=false;
var liveTimeout = null;

function activateSearch() {
	var searchForm = $('ajaxSearch_form');
    if (searchForm) {
		$('ajaxSearch_form').onsubmit = function() { doSearch(); return false; };
		
        var i = new Element('img');
		i.setProperties({
		   src: 'assets/snippets/AjaxSearch/images/indicator.white.gif', //Loading Image
		   alt: 'loading',
		   id: 'indicator'
		});
		toggleImage(i);
		
		searchForm.appendChild(i);

        var c = new Element('img'); //Close Image
		c.setProperties({
		   src: 'assets/snippets/AjaxSearch/images/cross.png', 
		   alt: 'close search',
		   id: 'searchClose'
		});
		c.addEvent('click', function(){closeSearch();});

        if (liveSearch) {
			c.setStyles({
			   position: 'absolute',
			   top: '1px',
			   right: '1px'
			});
        } else {
            toggleImage(c);
        }
		
		var s = $('ajaxSearch_output');
		
        var n = new Element('div'); // New search results div
		n.setProperty('id', 'current-search-results');
		n.setStyle('opacity', '1 !important');
		s.appendChild(n);
		newToggle = new Fx.Slide('current-search-results', {duration: 600}).hide();
		newToggle.isDisplayed = function() {
			return this.wrapper['offset'+this.layout.capitalize()] > 0;
		}
		
        if (liveSearch) {
			s.appendChild(c);
		} else {
			searchForm.appendChild(c);
		}        
        
        is_searching = false;
        search_open = false;
        if (liveSearch) {
			$('ajaxSearch_input').addEvent('keyup', liveSearchReq);
            $('ajaxSearch_submit').style.opacity = '0'; 
        }
    }
}

function liveSearchReq() {
	if (liveTimeout) {
		window.clearTimeout(liveTimeout);
	}
	liveTimeout = window.setTimeout("doSearch()",400);
}

function doSearch() {
    // If we're already loading, don't do anything
    if (is_searching) return false;
    s = $('ajaxSearch_input').value;
    // Same if the search is blank
    if (s == '') return false;
    is_searching = true;
    c = $('current-search-results');

	toggleImage($('indicator'));
    if (!liveSearch) {if (!search_open) {toggleImage($('searchClose'));}}
    search_open = true;
    b = $('ajaxSearch_submit');
    b.disabled = true;
	
	if (newToggle.isDisplayed()) {
		newToggle.toggle(); 
	}
	
    // Setup the parameters and make the ajax call
	var pars = Object.toQueryString({
		q: 'assets/snippets/AjaxSearch/AjaxSearch.php',
		search: unescape( encodeURIComponent( s ) ), 
		maxResults: maxResults,
		stripHtml: stripHtml,
		stripSnip: stripSnip,
		stripSnippets: stripSnippets,
		useAllWords: useAllWords,
		searchStyle: escape(searchStyle),
		minChars: minChars,
		showMoreResults: showMoreResults,
		moreResultsPage: moreResultsPage,
		as_language: as_language,
		extract: extract,
		docgrp: escape(docgrp),
		highlightResult: highlightResult
	});

    var ajaxSearchReq = new Ajax('index-ajax.php', {postBody: pars, onComplete: doSearchResponse});
	if (newToggle.isDisplayed()) {
		newToggle.toggle(); 
		ajaxSearchReq.request.delay(600, ajaxSearchReq);
	} else {
		ajaxSearchReq.request();
	}
    return true;
}

function doSearchResponse(request) {
    var o = $('ajaxSearch_output');
    o.style.opacity = '1';
    $('current-search-results').setHTML(decodeURIComponent( escape( request ) ));
	newToggle.toggle();
	is_searching = false;
	setTimeout('resetForm()',600);
}

function resetForm() {
    s = $('ajaxSearch_submit');
    s.disabled = false;
    toggleImage($('indicator'));
}

function closeSearch() {
	newToggle.toggle();
	setTimeout('clearSearch()',600);
}

function clearSearch() {
  toggleImage($('searchClose'));
  search_open = false;
  $('current-search-results').innerHTML = '';
  var o = $('ajaxSearch_output');
  o.style.opacity = '0';
  $('ajaxSearch_input').value="";
  $('ajaxSearch_input').focus();
}

function toggleImage(imgElement) {
	imgStyle = imgElement.getStyle('opacity');
	if (imgStyle == '0') {
		imgElement.setStyle('opacity', '1');
	} else {
		imgElement.setStyle('opacity', '0');
	}
}

//Event.observe(window, 'load', activateSearch, false);
Window.onDomReady(activateSearch);







onload = function runScript() {
    if (document.getElementById) {
        hideClass();
    } else {
        return true;
    }
}

function hideClass() {
	var e, i = 0;
	while (e = document.getElementsByTagName ('*')[i++]) {

		if (/\bhide\b/.test (e.className)) {
	        e.style.display = "none";
		}
	}
}

//hide everything except the specified element
function showIt(id) {
    var object = document.getElementById(id).style;
    if(document.getElementById("preamble")){
        document.getElementById("preamble").style.display = "none";
    }
    hideClass();
    object.display = "block";
}

function hideIt(id) {
    var object = document.getElementById(id).style;
    if(document.getElementById("preamble")){
        document.getElementById("preamble").style.display = "block";
    }
    hideClass();
    object.display = "none";
}

//hide everything except the specified element, then fade it in.
function fadeIt (millisec, id) {
	showIt(id);
    changeOpac(0, id);
	opacity(id, 0, 99, 1000);
}

//if an element is hidden, show it, else make it hidden
function showToggle(id) {
    var object = document.getElementById(id).style;
    if (object.display == "none") {
      object.display = "block";
      } else {
      object.display = "none";
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
	var object = document.getElementById(id).style;
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

function opacity(id, opacStart, opacEnd, millisec) {
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;

	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd) {
		for(i = opacStart; i >= opacEnd; i--) {
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	} else if(opacStart < opacEnd) {
		for(i = opacStart; i <= opacEnd; i++)
			{
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	}
}

function shiftOpacity(id, millisec) {
	//if an element is invisible, make it visible, else make it invisible
	if(document.getElementById(id).style.opacity == 0) {
		opacity(id, 0, 99, millisec);
	} else {
		opacity(id, 99, 0, millisec);
         }
}

function blendImage(divid, imageid, imagefile, millisec) {
	var speed = Math.round(millisec / 100);
	var timer = 0;

	//set the current image as background
	document.getElementById(divid).style.backgroundImage = "url(" + document.getElementById(imageid).src + ")";
	
	//make image transparent
	changeOpac(0, imageid);
	
	//make new image
	document.getElementById(imageid).src = imagefile;

	//fade in image
	for(i = 0; i <= 99; i++) {
		setTimeout("changeOpac(" + i + ",'" + imageid + "')",(timer * speed));
		timer++;
	} 
}

function currentOpac(id, opacEnd, millisec) {
	//standard opacity is 100
	var currentOpac = 100;
	
	//if the element has an opacity set, get it
	if(document.getElementById(id).style.opacity < 100) {
		currentOpac = document.getElementById(id).style.opacity * 100;
	}

	//call for the function that changes the opacity
	opacity(id, currentOpac, opacEnd, millisec);
}

function picInfo(whichpic, divid, imageid, imagefile, millisec) {
    if (document.getElementById) {
        blendImage(divid, imageid, imagefile, millisec);
  
        if (whichpic.title) {
            document.getElementById('desc').childNodes[0].nodeValue = whichpic.title;
            } else {
                document.getElementById('desc').childNodes[0].nodeValue = whichpic.childNodes[0].nodeValue;
            } 
        return false;

    } else {
        return true;
    }
}
