
AbtConfigs = {
	'RESULTS_PER_PAGE': '5',
	'LOCALE': 'de_DE',
	'SERVICE_URL': 'http://sitesearch.abbott.com/globalsearch/standardSearchService.do?',
	'MAX_DOCS': '500',
	'PAGES_PER_BLOCK': 5
}

function getURLParam(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 format(elementId, key) {
	var element;
	
	/* alert('message received');	 */
	element = document.getElementById(elementId);
	if ( element != null ) {
		element.innerHTML = abtTranslate(key);
	}	
}

function abtTranslate(key) {
	var noTranslation = "no translation found";
	var translation = Appcelerator.Localization.get(key, noTranslation, 
					Appcelerator.Localization.currentLanguage);
	if ( translation != noTranslation ) {
		return translation;
	}
	else if ( translation == noTranslation &&
		Appcelerator.Localization.currentLanguage != "en_US" && Appcelerator.Localization.currentLanguage != "de_DE") {
		/* return en_US translation, since foreign locale bundle doesn't exist */
		return Appcelerator.Localization.get(key, noTranslation, "en_US");
	}
	else {
		return translation;
	}
}

function SearchQuery() {
	/* public properties */
	this.queryText = "";
	this.narrowBy = "";
	this.resultStart = "";
	this.collections = "";
	this.sortBy = "";
	this.locale = "";
	this.resultsPerPage = "";
	this.maxDocs = "";		
}

function SearchResult(data) {
	var data = data;
	
	/* all values from echo are string and must be parsed */
	this.getLastDocument = function() {
		if(data.totalHits == 0) {
			s_abt.prop31 = 'zero';
		} 
		else 
		{
			s_abt.prop31 = data.totalHits;
		}
		var s_code = s_abt.t();if(s_code)document.write(s_code)
		if ( (parseInt(data.echo.resultStart) + data.documents.length - 1) < data.totalHits) {
			return parseInt(data.echo.resultStart) + data.documents.length - 1;
		}
		else {
			return data.totalHits;
		}		
	}
	
	this.getTotalPages = function() {		
		var totalPages = Math.ceil(data.totalHits / parseInt(data.echo.resultsPerPage));
		return totalPages;
	}
	
	this.getCurrentPage = function() {
		var resultStart = parseInt(data.echo.resultStart);
		var resultsPerPage = parseInt(data.echo.resultsPerPage);
		var currentPage = Math.floor( (resultStart-1) / resultsPerPage) + 1;
		
		return currentPage;		
	}
	
	this.getJSONPages = function() {
		var pages = "";
		var jsonObject;
		var currentPage;
		var currentPageBlock;
		var lastPage;
		var startPage;
		
		/* need to display sets of pages and not all available
		 * pages at once
		 */
		currentPage = this.getCurrentPage();		
		currentPageBlock = Math.floor((currentPage-1)/AbtConfigs.PAGES_PER_BLOCK);
		startPage = currentPageBlock * parseInt(AbtConfigs.RESULTS_PER_PAGE) + 1;
		lastPage = startPage + AbtConfigs.PAGES_PER_BLOCK - 1;
		if ( lastPage > this.getTotalPages() ) {
			lastPage = this.getTotalPages();
		}
		/* alert("startPage = " + startPage + "\nlastPage = " + lastPage); */
		
		pages = "[";
		/* alert("totalPages: " + this.getTotalPages()); */
		for( var i=startPage; i<=lastPage; i=i+1) {
			if ( i != startPage ) {
				pages = pages + ", ";
			}
			pages = pages + "{'page': '" + i + "', 'currentPage': ";
			if ( i == this.getCurrentPage() ) {
				pages = pages + "true";
				pages = pages + ", 'notCurrentPage': false"
			}
			else {
				pages = pages + "false";
				pages = pages + ", 'notCurrentPage': true"
			}
			pages = pages + "}";
		}
		pages = pages + "]";		
		jsonObject = eval('(' + pages + ')');
				
		return jsonObject;
	}
	
	this.hasPrevious = function() {
		if ( parseInt(data.echo.resultStart) > 1 ) {
			return true;
		}
		else {
			return false;
		}
	
	}
	
	this.hasNext = function() {
			if ( parseInt(data.echo.resultStart) + data.documents.length - 1 < data.totalHits ) {
				return true;
			}
			else {
				return false;
			}
		
	}
	
	
}

/*
 * Enables cross domain AJAX call
 */
function ajaxCallBack(url) {
	        clearTimeout(staticTimeout);
		staticTimeout = setTimeout("abtAjaxTimeout()", 8000);
		var head = document.getElementById('head');
		var script = document.createElement("script");
		script.setAttribute("type", "text/javascript");
		script.setAttribute("src", url);
		head.appendChild(script);
		/* set a timeout in case callback never occurs, e.g. bad URL no/server response */
}

/*
* JSON aware callback function
*/
function abtAjaxResponse(json) {
	/* response received so cancel the timeout, otherwise error message will be displayed */
	clearTimeout(staticTimeout);
	$MQ("l:ajaxCall.response", {"jsonObject": json});	
}

function abtAjaxTimeout() {
	/* javascript dynamically loaded but callback never occurred, trigger error */
 	$MQ("l:httpServiceError", null);
}
var staticTimeout;

var unreserved = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.~";
var reserved = "!*'();:@&=+$,/?%#[]";
var allowed = unreserved + reserved;
var hexchars = "0123456789ABCDEFabcdef";

// This function returns a percent sign followed by two hexadecimal digits.
// Input is a decimal value not greater than 255.
function gethex(decimal) {
  return "%" + hexchars.charAt(decimal >> 4) + hexchars.charAt(decimal & 0xF);
  }

function urlEncode(decoded) {
  var encoded = "";

  // ---------------- If UTF-8 character encoding was chosen: ----------------

    for (var i = 0; i < decoded.length; i++ ) {
      var ch = decoded.charAt(i);
      // Check if character is an unreserved character:
      if (unreserved.indexOf(ch) != -1) {
        encoded = encoded + ch;
      } else {

        // The position in the Unicode table tells us how many bytes are needed.
        // Note that if we talk about first, second, etc. in the following, we are
        // counting from left to right:
        //
        //   Position in   |  Bytes needed   | Binary representation
        //  Unicode table  |   for UTF-8     |       of UTF-8
        // ----------------------------------------------------------
        //     0 -     127 |    1 byte       | 0XXX.XXXX
        //   128 -    2047 |    2 bytes      | 110X.XXXX 10XX.XXXX
        //  2048 -   65535 |    3 bytes      | 1110.XXXX 10XX.XXXX 10XX.XXXX
        // 65536 - 2097151 |    4 bytes      | 1111.0XXX 10XX.XXXX 10XX.XXXX 10XX.XXXX

        var charcode = decoded.charCodeAt(i);

        // Position 0 - 127 is equal to percent-encoding with an ASCII character encoding:
        if (charcode < 128) {
          encoded = encoded + gethex(charcode);
        }

        // Position 128 - 2047: two bytes for UTF-8 character encoding.
        if (charcode > 127 && charcode < 2048) {
          // First UTF byte: Mask the first five bits of charcode with binary 110X.XXXX:
          encoded = encoded + gethex((charcode >> 6) | 0xC0);
          // Second UTF byte: Get last six bits of charcode and mask them with binary 10XX.XXXX:
          encoded = encoded + gethex((charcode & 0x3F) | 0x80);
        }

        // Position 2048 - 65535: three bytes for UTF-8 character encoding.
        if (charcode > 2047 && charcode < 65536) {
          // First UTF byte: Mask the first four bits of charcode with binary 1110.XXXX:
          encoded = encoded + gethex((charcode >> 12) | 0xE0);
          // Second UTF byte: Get the next six bits of charcode and mask them binary 10XX.XXXX:
          encoded = encoded + gethex(((charcode >> 6) & 0x3F) | 0x80);
          // Third UTF byte: Get the last six bits of charcode and mask them binary 10XX.XXXX:
          encoded = encoded + gethex((charcode & 0x3F) | 0x80);
        }

        // Position 65536 - : four bytes for UTF-8 character encoding.
        if (charcode > 65535) {
          // First UTF byte: Mask the first three bits of charcode with binary 1111.0XXX:
          encoded = encoded + gethex((charcode >> 18) | 0xF0);
          // Second UTF byte: Get the next six bits of charcode and mask them binary 10XX.XXXX:
          encoded = encoded + gethex(((charcode >> 12) & 0x3F) | 0x80);
          // Third UTF byte: Get the last six bits of charcode and mask them binary 10XX.XXXX:
          encoded = encoded + gethex(((charcode >> 6) & 0x3F) | 0x80);
          // Fourth UTF byte: Get the last six bits of charcode and mask them binary 10XX.XXXX:
          encoded = encoded + gethex((charcode & 0x3F) | 0x80);
        }

      }

    }  // end of for ...
   
   return encoded;

}

function createCookie(name,value,days) {
	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;
}

if ( readCookie("searchPerformed") == null ) {
	var searchPerformed = false;
}
else {
	var searchPerformed = true;
}

var abtStaticQuery;
var abtSearchResults;

function getStaticSearchResults() {
	return abtSearchResults;
}

function setStaticSearchResults(searchResults) {
	abtSearchResults = searchResults;
}

function getStaticQuery(newQuery) {
	if (abtStaticQuery == null || newQuery) {
		var query = new SearchQuery();
		query.resultStart = '1';
		query.resultsPerPage = AbtConfigs.RESULTS_PER_PAGE;
		query.locale = AbtConfigs.LOCALE;
		abtStaticQuery = query;
	}

	return abtStaticQuery;

}

