	if (!('console' in window && 'firebug' in console)) {
		window.console = {};
		var methods = ['log','debug','info','warn','error','assert','dir','dirxml','group','groupEnd','time','timeEnd','count','trace','profile','profileEnd'];
		for (var i = 0; i < methods.length; i++)
			window.console[methods[i]] = function() {};
	}


	var expdate = new Date();
	expdate.setTime(expdate.getTime() +  (24 * 60 * 60 * 1000 * 31 * 12));
	
// AUDIO PLAYER

	var ap_instances = new Array();
	
	function ap_stopAll(playerID) {
		for(var i = 0;i<ap_instances.length;i++) {
			try {
				if(ap_instances[i] != playerID) document.getElementById("audioplayer" + ap_instances[i].toString()).SetVariable("closePlayer", 1);
				else document.getElementById("audioplayer" + ap_instances[i].toString()).SetVariable("closePlayer", 0);
			} catch( errorObject ) {
				// stop any errors
			}
		}
	}
	
	function ap_registerPlayers() {
		var objectID;
		var objectTags = document.getElementsByTagName("object");
		for(var i=0;i<objectTags.length;i++) {
			objectID = objectTags[i].id;
			if(objectID.indexOf("audioplayer") == 0) {
				ap_instances[i] = objectID.substring(11, objectID.length);
			}
		}
	}
	
	var ap_clearID = setInterval( ap_registerPlayers, 100 );


//TOOGLE BOX VIEWS

	function toggle(element, cookieVal, defStatus)
	{	
	    var status = getCookie('langBox_'+cookieVal);
	    if(status==1 || (status == null && defStatus == 0))
		{
			document.getElementById(element).style.overflow='visible';
			document.getElementById(element).style.height='';
			document.getElementById(element+"Arrow").innerHTML = '<img src="/images/blueboxArrowOpen.jpg" border="0" />';
			setCookie('langBox_'+cookieVal,0, expdate, '/');
		}
		else
		{
		    document.getElementById(element).style.overflow='hidden';
		    document.getElementById(element).style.height='0px';
			document.getElementById(element+"Arrow").innerHTML ='<img src="/images/blueboxArrowClosed.jpg" border="0" />';	
			//delCookie('langBox_'+cookieVal);
			setCookie('langBox_'+cookieVal,1, expdate, '/');			
		}
	}

//COOKIE FUNCTIONS

	function setCookie(name, value, expires, path, domain, secure) {
	  document.cookie = name + "=" + escape(value) +
	  ((expires == null) ? "" : "; expires=" + expires) +
	  ((path == null) ? "" : "; path=" + path) +
	  ((domain == null) ? "" : "; domain=" + domain) +
	  ((secure == null) ? "" : "; secure");
	}

	function getCookie(name)
	{
	  var cname = name + "=";
	  var dc = document.cookie;
	  if (dc.length > 0) {
		begin = dc.indexOf(cname);
		if (begin != -1) {
		  begin += cname.length;
		  end = dc.indexOf(";", begin);
		  if (end == -1) end = dc.length;
			return unescape(dc.substring(begin, end));
		}
	  }
	  return null;
	}

	function delCookie (name,path,domain)
	{
	  if (getCookie(name)) {
		document.cookie = name + "=" +
		((path == null) ? "" : "; path=" + path) +
		((domain == null) ? "" : "; domain=" + domain) +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	  }
	}

//SET TEXT SIZE

	function textSize(type)
	{
		if(getCookie('txt') != null)
			offset = parseInt(getCookie('txt'));
		else
			offset = 0;
		
		if(type == '+' && offset < mx)
		{
			offset++;
			if(offset < mx)
				document.getElementById('textIncrease').innerHTML = '<img src="/images/textEnlargeActive.gif" border="0" height="13" width="13" />';
			else
				document.getElementById('textIncrease').innerHTML = '<img src="/images/textEnlargeInactive.gif" border="0" height="13" width="13" />';
			document.getElementById('textDecrease').innerHTML = '<img src="/images/textShrinkActive.gif" border="0" height="13" width="13" />';	
			setClass("ayah", 1*inc);
		}
		else if(type == '-' && offset > mn)
		{
			offset--;
			if(offset > mn)
				document.getElementById('textDecrease').innerHTML = '<img src="/images/textShrinkActive.gif" border="0" height="13" width="13" />';
			else
				document.getElementById('textDecrease').innerHTML = '<img src="/images/textShrinkInactive.gif" height="13" width="13" border="0" />';
			document.getElementById('textIncrease').innerHTML = '<img src="/images/textEnlargeActive.gif" height="13" width="13" border="0" />';	
			setClass("ayah", -1*inc);
		}
		setCookie('txt',offset, expdate, '/');
	}

//UPDATE TEXT SIZES

	function setClass(theClass,size)
	{
		var allPageTags=document.getElementsByTagName("*");
		for (var i=0; i<allPageTags.length; i++)
		{
			if (allPageTags[i].className.match(new RegExp('^'+ theClass)))
			{
				var fontChange = allPageTags[i].style.fontSize;
				var heightChange = allPageTags[i].style.lineHeight;
				allPageTags[i].style.fontSize = (parseInt(fontChange.replace(/px/,''))+size)+"px";
				allPageTags[i].style.lineHeight = (parseInt(heightChange.replace(/px/,''))+size)+"px";
				if (theClass == 'ayah' && allPageTags[i].className.match(/text/)) {
					var div = jQuery(allPageTags[i]).find('>div');
					if (div.length) {
						div = div.get(0);
						div.style.fontSize = (parseInt(div.style.fontSize.replace(/px/,'')) + size) + 'px';
						div.style.lineHeight = (parseInt(div.style.lineHeight.replace(/px/,'')) + size) + 'px';
					}
				}
			}
		}
		if (document.getElementById('bismillah'))
			document.getElementById('bismillah').style.fontSize = (parseInt(document.getElementById('bismillah').style.fontSize.substring(0,document.getElementById('bismillah').style.fontSize.indexOf('px')))+size)+"px";
	}

//CHANGE SURAH

	function changeSurah(surah)
	{
		location='/'+surah;
	}

//SEARCH BOX TIPS

	function popSearchBox()
	{
		var searchBox = document.getElementById('searchBoxTips');
		var canvas = document.getElementById('canvas');
		var html  = '<div id="popup"><div id="popupHeader"><div id="popupClose" onClick="javascript:popSearchBox();"><img src="/images/close.gif" border="0" alt="Close" /></div>Ways to Search the Qur\'an</div><div id="popupBody"><h1>Search by Specific Chapter, Verse </h1><blockquote><p>Enter a surah number and/or an ayah or ayah range in the search bar:</p><table cellpadding=0 cellspacing=0 border=0><tr><th width="115">Example Search</th><th width="300">Returns</th></tr><tr><td>1</td><td>Chapter 1 of the Qur\'an </td></tr><tr><td>4:12</td><td>Chapter 4, Verse 12 of the Qur\'an </td></tr><tr><td>10:5-9</td><td>Chapter 10, Verses 5 through 9 of the Qur\'an </td></tr></table></blockquote><h1>Word or Phrase Search</h1><blockquote><p>Enter a word or phrase in any language:</p><table cellpadding=0 cellspacing=0 border=0><tr><th width="115">Example Search</th><th width="300">Returns</th></tr><tr><td>believer</td><td>Any instance of "believer" in all translations </td></tr><tr><td>"O you who believe"</td><td>Any instance of "O you who believe" in all translations </td></tr><tr><td>"&#1610;&#1575; &#1571;&#1610;&#1607;&#1575; &#1575;&#1604;&#1584;&#1610;&#1606; &#1570;&#1605;&#1606;&#1608;&#1575;"</td><td>Any instance of &quot;&#1610;&#1575; &#1571;&#1610;&#1607;&#1575; &#1575;&#1604;&#1584;&#1610;&#1606; &#1570;&#1605;&#1606;&#1608;&#1575;&quot; in Arabic</td></tr></table></blockquote><h1>Phonetic Search</h1><blockquote>'
		//+'Phonetic search coming soon.'+
		+'<p>Enter a word or phrase to search transliteration: </p><table cellpadding=0 cellspacing=0 border=0><tr><th width="425">Example Search</th></tr><tr><td>bismillah ar rahman ar rahim </td></tr><tr><td>ya ayuhal lathina amanu </td></tr></table>'
		+'</blockquote></div></div>';
		
		if(searchBox.style.visibility == '')
		{
			visible = 'visible';
		}
		else
		{
			if(searchBox.style.visibility == 'hidden')		visible = 'visible';
								else						visible = 'hidden';
		}
		
		if(visible == 'visible')
		{
			searchBox.innerHTML = html;
			canvas.style.height = "100%";
		} else	canvas.style.height = "0px";

		searchBox.style.visibility = visible;
		canvas.style.visibility = visible;
	}
	
//SHOW MORE SEARCH AYAHS

	function expandAyat(trigger,box){
		trigger.innerHTML = (trigger.innerHTML ==  "show all" ? "show first" : "show all");

		document.getElementById(box).style.display = (document.getElementById(box).style.display == "block" ? "none" : "block");
		
	}

//AJAX INITIALIZE

	function outputLanguage()
	{
		var l = [];
		jQuery('input[id^=lang_]').each(function() {
			var id = jQuery(this).attr('id').replace(/^lang_/,'');
			if (jQuery(this).is(':checked'))
				l.push(id);
		});
		l = l.join(',');
		
      var key;
      if (!sA && !eA) {
         key = $('#quranOutput').find('> a.key:last').attr('name');
         if (key) { eA = parseInt(key.replace(/^.*:/,'')) + 1; }
         sA = 1;
      }
				
		document.getElementById("statusContainer").style.display = 'block';
		jQuery.getJSON('/quran/ajax', {
			s: s,
			sA: sA,
			eA: eA,
			l: l,
         json: 1
		}, function(response) {
			var languages = {};
			jQuery.each(response.languages, function(i, language_id) {
				language_id = parseInt(language_id);
				languages[language_id] = false;
				jQuery('#lang_'+ language_id).attr('checked', 'checked');
			});
			jQuery('#quranOutput > div.verse > div.ayah').each(function() {
				var me = jQuery(this);
				var language_id = me.attr('class').replace(/^.*language_([\d]+).*$/,"$1");
				if (jQuery.inArray(language_id, response.languages) == -1)
					me.hide();
				else {
					me.show();
					languages[language_id] = true;
				}
			});
			jQuery.each(response.verses, function(verse_id, verse_data) {
				jQuery.each(verse_data, function(language_id, language_data) {
					language_id = parseInt(language_id);
					if (!languages[language_id]) {
						var tmpl = jQuery(template('language_tmpl', language_data));
						var target = jQuery('#verse_'+ verse_id);
						var after_id;
						jQuery.each(languages, function(id, val) {
							if (id > language_id) {
								return 0;
							} else
							if (id < language_id) {
								after_id = id;
							}
						});
						if (after_id) {
							tmpl.insertAfter(jQuery('#verse_'+ verse_id +'_language_'+ after_id));
						}
						else {
							target.append(tmpl);
						}
					}
				});
			});
			document.getElementById("statusContainer").style.display = 'none';
		});
	}

	var template_cache = {};

	function template(str, data) { // Simple JavaScript Templating, John Resig - http://ejohn.org/ - MIT Licensed
		var fn = !/\W/.test(str) ? template_cache[str] = template_cache[str] || template(document.getElementById(str).innerHTML) : new Function(
			"obj",
			"var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('" +
				str
					.replace(/[\r\t\n]/g, " ")
					.split("<%").join("\t")
					.replace(/((^|%>)[^\t]*)'/g, "$1\r")
					.replace(/\t=(.*?)%>/g, "',$1,'")
					.split("\t").join("');")
					.split("%>").join("p.push('")
					.split("\r").join("\\'") +
			"');}return p.join('');"
		);
		
		return data ? fn( data ) : fn;
	};

window.quran = {
	_: {
		l: ''
	}
};

$(function() {
		function build_languages() {
			window.quran._.l = window.quran._.l.replace(/^,/,'').replace(/,$/,'');
			var id = jQuery(this).attr('id').replace(/^lang_/,'');
			if (jQuery(this).is(':checked')) {
				window.quran._.l = window.quran._.l.split(/,/);
				window.quran._.l.push(id);
				window.quran._.l = window.quran._.l.join(',');
			}
			else {
				var re1 = new RegExp(',' + id + '()$'),
				    re2 = new RegExp('^' + id + ',()'),
				    re3 = new RegExp(',' + id + '(,)'),
				    re4 = new RegExp('^' + id + '()$');
				window.quran._.l = window.quran._.l.replace(re1,'$1').replace(re2,'$1').replace(re3,'$1').replace(re4,'$1');
			}
			window.quran._.l = window.quran._.l.replace(/^,/,'').replace(/,$/,'');
		};
		jQuery('input[id^=lang_]').each(function() {
			build_languages.apply(this, arguments);
			$(this).click(function() {
				build_languages.apply(this, arguments);
			});
		});
});

$(function() {
	if (s && !sA) { // if 'surahID' is set and 'startAyah' is not set
	                // then we're on an entire surah's page, e.g. quran.com/2
	                // and this is the only time we actually want to use this
		var _ = {
			output: $('#quranOutput'),
			indicator: $('#scrolling'),
			window: $(window),
			document: $(document),
			waiting: false,
			end_reached: false
		};

		function infinite_scroll() {
			_.indicator.css('visibility','visible');
			_.waiting = true;

			var key;
			if (!_.s && !_.sA && !_.eA) {
				key = _.output.find('> a.key:last').attr('name');
				if (key) {
					_.s = parseInt(key.replace(/:.*$/,''));
					_.sA = parseInt(key.replace(/^.*:/,'')) + 1;
					_.eA = parseInt(key.replace(/^.*:/,'')) + 20;
				}
			}

			if (_.s && _.sA && _.eA) {
				if (!_.first_run)
					_.first_run = true;
				else {
					_.sA += 20;
					_.eA += 20;
				}

				$.get('/quran/ajax', {
					s: _.s,
					sA: _.sA,
					eA: _.eA,
					l: window.quran._.l
				}, function(data, success) {
					if (success) {
						if (data != ''){
							_.output.find('> div.verse:last').after(data);
							eA = _.eA;
										sA = 1;
						}
						else {
							_.end_reached = true;
							_.window.unbind('scroll');
						}

						if (!_.end_reached && _.window.scrollTop() == _.document.height() - _.window.height())
							_.window.scrollTop(_.window.scrollTop() - 60);

						_.indicator.css('visibility','hidden');
						_.waiting = false;
					}
					else {
						_.indicator.css('visibility','hidden');
						_.waiting = false;
					}
				});
			}
			else {
				_.indicator.css('visibility','hidden');
				_.waiting = false;
			}
		};

		if (_.window.scrollTop() == 0 || !_.end_reached && !_.waiting && _.window.scrollTop() >= (_.document.height() - _.window.height() - 960))
			infinite_scroll();

		_.window.bind('scroll', function() {
			if (!_.end_reached && !_.waiting && _.window.scrollTop() >= (_.document.height() - _.window.height() - 960))
				infinite_scroll();
		});
	}
});


