//------------------------- Copyright Block --------------------------
/* 
Tanzil Quran Navigator (ver 0.9.1)

Copyright (C) 2008 Hamid Zarrabi-Zadeh

http://tanzil.info

This program is free software: you can redistribute it and/or modify

it under the terms of the GNU General Public License as published by

the Free Software Foundation, either version 3 of the License, or

(at your option) any later version.

This program is distributed in the hope that it will be useful,

but WITHOUT ANY WARRANTY; without even the implied warranty of

MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

GNU General Public License for more details.

The above copyright block and permission notice shall be included 

in all copies or substantial portions of this program.

*/
//--------------------------------------------------------------------

//----------------------------- Globals ------------------------------

var version = '0.1.4';

var textTools = new TextTools();

var localSearch = false;

var audioEnabled = true;

var resultsPerPage = 20;

var searchResults = null;

var highlightAya = false;

var page_response = "";

var wait_period = "";

var repeatVerse = 1;

var wait_period = 1;

var showJuzz = "";

var continueRecitation = "";

var displayMode = 14;

var currSura = 1;

var currAya = 1;

var currWord = 1;

var wbw_currSura = 1;

var wbw_currAya = 1;

var wbw_currWord = "00001";

var wbwPlay = "";

var loadedAya = ''

var isIE = (navigator.appName == "Microsoft Internet Explorer");

var isOldBrowser = !window.XMLHttpRequest;  // IE6 and older browsers

var defJustify = isIE || document.getElementsByClassName; // Firefox 3.0

var searchType = 0;

//---------------------- Initialization -----------------------

// initialize 

function initPage(start)
{
	initSurahList();

	initJuzList();

	initAyaList($('surahList').value* 1, 1);

	loadRootsList();

	if (audioEnabled)
		initAudioPlayer();

	showSura(1,-1);
}


//---------------------- Init Menus -----------------------

// init sura menu

function initSurahList(sura, nameType)
{
	var items = [];

	nameType = nameType || 'name'  

	for (var i=1 ; i<=Quran.numSuras ; i++)
		items.push( {text: i+ '. '+ Quran.getSuraName(i, nameType), value: i} );
	initMenu('surahList', items, sura);	
}

// init aya menu

function initAyaList(sura, aya)
{
	var numAyas = Quran.suraProps(sura).ayas;

	if ($('ayaList').childNodes.length == numAyas)
		return;

	var items = [];

	for (var i=1 ; i<=numAyas ; i++)
		items.push( {text: i, value: i} );

	initMenu('ayaList', items, aya);	
}

// init juz menu

function initJuzList()
{
	var items = [];
	for (var i=1 ; i<=Quran.numJuzs ; i++)
		items.push( {text: i, value: i} );

	initMenu('juzList', items);	
}

// init trans menu

function initTransMenu()
{
	var items = [];

	for (var i=0 ; i<transList.length ; i++)
		items.push( {text: transList[i].lang+ ':  '+ transList[i].name, value: transList[i].id} );

	initMenu('transMenu', items, currTrans);	
}


// retrieves items from an array

function getItems(theArray, textLabel, valueLabel)
{
	var items = [];

	for (var i=0 ; i<theArray.length ; i++)
		items[i] = {text: theArray[i][textLabel], value: theArray[i][valueLabel] || i};

	return items;	
}

// init a menu with items
function initMenu(menuID, items, defVal)
{
	var menu = $(menuID);
	var newMenu = document.createElement('select');
	var attr = ['id', 'className', 'class', 'onchange'];
	for (var i in attr) {
		newMenu[attr[i]] = menu[attr[i]];
		//newMenu.setAttribute(attr[i], menu.getAttribute(attr[i]));
	}
	for (var i=0 ; i<items.length ; i++) {
		var text = items[i].text;
		var option = document.createElement('option');
		option.text = option.innerHTML = text;
		option.value = items[i].value;
		newMenu.appendChild(option);
		if (defVal && defVal == items[i].value)
			newMenu.selectedIndex = i;
	}
	menu.parentNode.replaceChild(newMenu, menu);
}

//---------------------- Show Contents -----------------------

// show page containing an aya

function displayAya(sura, aya, searchflag)
{
	nav = parent.document.getElementById('paging');
	nav.style.visibility = "hidden";
	nav.style.display = "none";

	nav = parent.document.getElementById('sura_navigation');
	nav.style.visibility = "visible";
	nav.style.display = "block";
	
	//scrollToAya(sura, aya);
	//var iframeEl = document.getElementById('frameText');
	//if ( iframeEl.contentDocument ) { // DOM
	//	iframeEl.contentWindow.scrollToAya(sura, aya);
	//} else if ( iframeEl.contentWindow ) { // IE win
	//	iframeEl.contentWindow.scrollToAya(sura, aya);
	//}
	
	currSura = sura;

	if(aya == -1)
		currAya = 1;
	else
		currAya = aya;

	var juz = Quran.getAyaJuz(sura, currAya);

	$('juzList').selectedIndex = juz- 1;

	initAyaList(sura, currAya);

	if (isOldBrowser)
		$('surahList').selectedIndex = sura- 1;
	else
		initSurahList(sura, 'name');
	
	$('ayaList').selectedIndex = currAya- 1;

	if(showJuzz == 1)
		aya = currAya;

	if(aya == -1 || showJuzz == 1)
		retrievePage(sura, aya, showJuzz);

	if(searchflag == -1)
		retrievePage(sura, aya, '-1');

	// Scroll to starting verse of selected Juzz
	if(showJuzz == 1)
		showJuzz = "";

	if (currSura+':'+currAya != loadedAya && audioEnabled && displayMode != 2)
		loadAudio();
	
	// Show Tafsir
	getTafsir(currSura, currAya);
}

// show aya

function showAya(sura, aya)
{
	sura = sura || $('surahList').value* 1;

	aya = aya || $('ayaList').value* 1;

	var iframeEl = document.getElementById('frameText');

	if ( iframeEl.contentDocument ) { // DOM
		iframeEl.contentWindow.showAya(sura, aya, displayMode);
	} else if ( iframeEl.contentWindow ) { // IE win
		iframeEl.contentWindow.showAya(sura, aya, displayMode);
	}

	// Show Tafsir
	getTafsir(sura, aya);
}

// UnSelect Previously selected Aya

function unselectPreviousAya()
{

}

// Select Next Aya

function selectNextAya(aya)
{
	var ayaDiv, cname;

	ayaDiv = "v"+ threeDigits(currSura)+ threeDigits(aya);

	if(displayMode == 4)
		cname = "ayaEnglishOnlySelected";
	else
		cname = "ayaSelected";

	var iframeMain = document.getElementById('frameText');

	if (iframeMain.contentDocument ) { // DOM
		iframeMain.contentDocument.getElementById(ayaDiv).className = cname;
	} else if ( iframeMain.contentWindow ) { // IE win
		iframeMain.contentWindow.document.getElementById(ayaDiv).className = cname;
	}
}

// scroll to aya

function scrollToAya(sura, aya)
{
	var ayaDiv = "";
	ayaDiv = "v"+threeDigits(sura)+threeDigits(aya);
	if(aya == -1)
	{
	}
	else
	{
		var iframeEl = document.getElementById('frameText');
		if ( iframeEl.contentDocument ) { // DOM
	        iframeEl.contentWindow.scrollToAya(sura, aya);
		} else if ( iframeEl.contentWindow ) { // IE win
			iframeEl.contentWindow.scrollToAya(sura, aya);
		}
	}	
}

// show sura

function showSura(sura, aya, nextChapter, navigate)
{
	var change_flag = "1";
    
	if(sura == -1)
	{
		sura = $('surahList').value * 1;
        
		if(sura < 115 && sura > 0)
		{
			if(navigate == 1 && sura < 114)
			{
				sura++;
				currSura++;
			}
			else if(navigate == -1 && sura > 1)
			{
				sura--;
				currSura++;
			}
			else
				change_flag = ""; //don't load any sura (the limits)
            
			if(change_flag == "1")
			{
				var juz = Quran.getAyaJuz(sura, 1);

				$('juzList').selectedIndex = juz- 1;

				initAyaList(sura, 1);

				$('surahList').selectedIndex = sura - 1;

				$('ayaList').selectedIndex = 0;
			}
		}
	}
	else
		sura = sura || $('surahList').value * 1;
    
	if(change_flag == "1")
	{
		var ayaDiv = "";
		
		if(nextChapter == 1)
			currSura--;
        
		ayaDiv = "v" + threeDigits(currSura) + threeDigits(1);
        
		if(displayMode == 2)
			ayaDiv = "w" + threeDigits(currSura) + threeDigits(1) + fourDigits(1);
		else if(displayMode == 10 || displayMode == 14)
			ayaDiv = "v" + threeDigits(currSura) + threeDigits(1) + threeDigits(1);
        
		var iframeEl = document.getElementById('frameText');
        
		if ( iframeEl.contentDocument ) { // DOM
			if(iframeEl.contentDocument.getElementById(ayaDiv))
				iframeEl.contentWindow.scrollToAya(sura, -1);
		} else if ( iframeEl.contentWindow ) { // IE win
			if(iframeEl.contentWindow.document.getElementById(ayaDiv))
				iframeEl.contentWindow.scrollToAya(sura, -1);
		}
        
		currSura = sura;
        
		displayAya(sura, -1);
	}
}


// show juz

function showJuz(juz)
{
	juz = juz || $('juzList').value* 1;

	showJuzz = 1;

	var iframeEl = document.getElementById('frameText');
	if ( iframeEl.contentDocument ) { // DOM
		iframeEl.contentWindow.scrollToAya(currSura, -1);
	} else if ( iframeEl.contentWindow ) { // IE win
		iframeEl.contentWindow.scrollToAya(currSura, -1);
	}

	displayAya(Quran.juzProps(juz).sura, Quran.juzProps(juz).aya);
}

//---------------------- Display Text -----------------------

// retrieve page contents

function retrievePage(sura, aya, showJuzz, modeFlag)
{
	if(aya == -1 || showJuzz == 1 || showJuzz == -1)
	{
		var sj = 1;
        
		if(showJuzz != 1)
			sj = 0;
        
		if(modeFlag == 1)
		{
			$('ayaList').selectedIndex = 0;
			var juz = Quran.getAyaJuz(sura, 1);
			$('juzList').selectedIndex = juz- 1;
		}		
        
		currSura = sura;
        
		currAya = 1;
        
		setRecitation();
        
		if(showJuzz == -1)
			frameText.location = "../quran.php?sura=" + currSura + "&aya=" + aya + "&mode=" + displayMode + "&showJuzz=1&cr=" + continueRecitation;
		else
			frameText.location = "quran.php?sura=" + currSura + "&aya=" + aya + "&mode=" + displayMode + "&showJuzz=" + sj + "&cr=" + continueRecitation;
        
		// Continue Recitation
        
		if(continueRecitation == 1)
			continueRecitation = "";
	}
}

// go to an aya 

function goToAya(sura, aya)
{
	displayAya(sura, aya, true);
}

//--------------------- Show Search Results --------------------

function showSearch(id)
{
	if(id == 0)
	return false;
	
	if(id==2)
	{
		var searchText = document.frm.rootList.value;	
		searchType = 2;
		frameText.location="search/arabic-root.php?searchText="+searchText;
	}
	else
	{
		var searchText = document.frm.searchText.value;	

		if(isAlphabetic(searchText))
		{
			searchType = 1;
			frameText.location="search/search.php?searchText="+searchText;
		}
		else
		{
			searchType = 3;

			var searchText = searchText;

			searchText = searchText.replace(/\-/g, '!');
			searchPattern = textTools.enrichPattern(searchText);
			searchText = searchPattern;
			
			frameText.location="search/arabic-search.php?searchText="+searchText;
		}

		//if (searchText.strip() == '') {
		//	alert('Search string is empty.');
		//	return;
		//}
		
		//searchText = searchText.replace(/\-/g, '!');	
		//document.searchForm.searchText.value = search ;
		//alert(search);		
		
		//frameText.location="search/search.php?searchText="+searchText;
		
		//frameText.location="search/arabic-search.php?searchText="+searchText;
		
		//frameText.location="search.php?searchText="+document.frm.searchText.value;
	}
}

function isAlphabetic(s)
{   
    var i;    
    var reAlphabetic = /^[a-zA-Z]+$/ ;
//    if(isEmpty(s))
//	{ 
//		return false;
       //if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       //else return (isAlphabetic.arguments[1] == true);
//	}
//    else 
//	{
       return reAlphabetic.test(s)
//    }
}

// start search query
function startSearch() 
{
	var search = $('searchText').value;
	if (search.strip() == '') {
		alert('Search string is empty.');
		return;
	}
	$('pageOffset').value = 1;
	$('searchPattern').innerHTML = search;

	search = search.replace(/\-/g, '!');
	searchPattern = textTools.enrichPattern(search);
	highlightPattern = searchPattern.replace(/[+!]/g, '|');
	highlightPattern = highlightPattern.replace(/^[|]+/g, ''); // remove leading |'s
	searchText = search;
	searchResults = null;

	try { new RegExp(highlightPattern, 'g'); } 
	catch(e) {
		alert('Search expression is invalid.'); 
		searchResults = {results: [], totalMatch: 0}; 
		searchPattern = '';
	}
	if (localSearch && !searchResults)
		searchResults = textTools.search(mainText, searchPattern);
	
	prepareResults();
}

function changePage(page, start, stext, id)
{
	if(id == 1)
		frameText.location="search/search.php?searchText="+stext+"&page="+page+"&start="+start;
	else if(id == 2)
		frameText.location="search/arabic-root.php?searchText="+stext+"&page="+page+"&start="+start;
}

function showPage(e)
{
	e.style.background='url(images/img_highlight_over.gif) no-repeat';
}


function loadRootsList()
{
	var Roots = [];

	var root = RootList.split(' ');

	for (var i=0 ; i<root.length/2 ; i++)
		Roots.push({chr: root[2*i], num: root[2*i+1]});

	var items = [];	

	for (var i=0 ; i<Roots.length ; i++)		
		items.push({ value: (i+1), text: Roots[i].chr }); //+ ' ['+ Roots[i].num+ ']'
    
	initMenu('rootList', items);
}

//---------------------- Audio Functions -----------------------

// initilize audio player

function initAudioPlayer() 
{
	//var so = new SWFObject('http://www.allahsquran.com/test123/audio/player/mediaplayer.swf','player','118','17','8');
    
	var width = '118';
	var height = '21';
    
	var so = new SWFObject('includes/swfplayer.swf','player',width,height,'8');
    
	so.addParam('allowscriptaccess','always');

	so.addParam('allowfullscreen','true');

	so.addParam('wmode','transparent');

	so.addParam('bgcolor','#FFFFFF');

	so.addParam('scale','noscale');

	so.addVariable('width',width);

	so.addVariable('height',height);

	so.addVariable('file', getAudioUrl(currSura, currAya, currWord));

	so.addVariable('backcolor','0xFFFFFF');

	so.addVariable('frontcolor','0x7e7e7e');

	so.addVariable('lightcolor','0x696969');

	so.addVariable('screencolor','0xdbdbdb');

	so.addVariable('javascriptid','player');

	so.addVariable('searchbar','false');

	so.addVariable('showdigits','false');

	so.addVariable('usefullscreen','false');

	so.addVariable('showstop ','false');

	so.addVariable('enablejs','true');

	so.write('mediaplayer');

	//loadAudio();
}

// get the player object

function getPlayer(player) 
{
	if (navigator.appName.indexOf("Microsoft") != -1)
	{
		return document[player];
	}
	else
		return document[player];
}

// send an event to player object

function sendEvent(typ, param) 
{ 
	var player = getPlayer('player');
    
	if (player && player.sendEvent)
		player.sendEvent(typ, param); 
}

// load a file to the player

function loadFile(obj) 
{
	var player = getPlayer('player');
	
	if (!player || !player.loadFile)
		return false;
    
	player.loadFile(obj); 
    
	return true;
}

// load an audio file to the player

function loadAudio()
{	
	if((displayMode == 2 || displayMode == 3 || displayMode == 6 || displayMode == 7 || displayMode == 10 || displayMode == 14) && wbwPlay == 1){
		var url = getAudioUrl(wbw_currSura, wbw_currAya, wbw_currWord);
        //alert("1 = " + url);
    } else {
		var url = getAudioUrl(currSura, currAya, currWord);
        //alert("2 = " + url);
    }
    
	if (loadFile( {file: url}) )
		loadedAya = currSura+ ':'+  currAya;
    else{
		setTimeout('loadFile({file: "'+ url+ '"})', 2000);
        //alert("else,," + url);
    }
}

// add zero padding to a number

function threeDigits(num)
{
    var temp = '000'+ num;
    return temp.substr(temp.length-3);
}

// add zero padding to a number

function fourDigits(num)
{
    var temp = '0000'+ num;
    return temp.substr(temp.length-4);
}

// get url of the audio file for given aya

function getAudioUrl(sura, aya, word)
{
	//var url = 'http://www.allahsquran.com/test123/audio/vbv/arabic/';

	if((displayMode == 2 || displayMode == 3 || displayMode == 6 || displayMode == 7 || displayMode == 10 || displayMode == 14) && wbwPlay == 1)
	{
		var url = 'http://audio.allahsquran.com//wbw/' + word + '.mp3';
	}
	else if(displayMode == 1 || displayMode == 3 || displayMode == 4 || displayMode == 5 || displayMode == 6 || displayMode == 7 || displayMode == 8 || displayMode == 10 || displayMode == 12 || displayMode == 14)
	{
		var url = 'http://audio.allahsquran.com/vbv/arabic/';
		url += 	document.frm["recitor"].value + '/';
		url += threeDigits(sura)+ threeDigits(aya)+ '.mp3';
	    //alert(url);
	}
	else
		url = "";

	return url;
}

// set current recitation 

function setRecitation()
{
    //alert("start setRecitation()");
	loadAudio();
    //alert("finish setRecitation()");
}

// start recitation

function recite()
{
	sendEvent('playpause');
}

// the callback funtion of the player

function getUpdate(typ, param1, param2, swf) 
{ 
	if (typ == 'time' && param1 != 0)
		wait_period = param1;

	if (typ == 'time') return;

	if (typ == 'load') lastLoad = param1;

	if (typ == 'state' && param1 == 3)
	{
		if(displayMode == 2 || wbwPlay == 1)
		{
			wbwPlay = "";
			setRecitation();
		}
		else
		{
			var next_verse = false;

			if(document.frm['next_verse'].checked == true)
				next_verse = true;

			for (i=0;i<document.frm.interval.length;i++)
			{
				if (document.frm.interval[i].checked) 
				{
					if(document.frm.interval[i].value == "continous")
						wait_period = 100;
					else if(document.frm.interval[i].value == "equaltoverse")
						wait_period = wait_period * 1000;
					else if(document.frm.interval[i].value == "vartime")
						wait_period = document.frm["wait_period"].value * 1000;
				}
			}

			var next_chapter = false;

			if(document.frm['next_chapter'].checked == true)
			{
				var numAyas = Quran.suraProps(currSura).ayas;
				if(currSura < 114 && currAya == numAyas)
				{
					next_chapter = true;
					currSura++;
					if(continueRecitation == 1)
						continueRecitation = "";
					else
						continueRecitation = 1;
					showSura(currSura,-1,1);
				}
			}

			if (!next_chapter && (next_verse || document.frm["repeatVerse"].value > 1) && lastLoad && goToNextAya())
				setTimeout('recite()', wait_period);
		}
	}
}

// go to next aya

function goToNextAya()
{
	if(repeatVerse < document.frm["repeatVerse"].value)
	{
		repeatVerse++;
		displayAya(currSura, currAya);
	}
	else
	{
		if(document.frm['next_verse'].checked == false)
		{
			repeatVerse = 1;
			return false;
		}

		var numAyas = Quran.suraProps(currSura).ayas;

		if(currAya < numAyas)
			++currAya;
		else
		{
			repeatVerse = 1;
			return false;
		}

		repeatVerse = 1;

		displayAya(currSura, currAya);

		var iframeEl = document.getElementById('frameText');

		if ( iframeEl.contentDocument ) { // DOM
				iframeEl.contentWindow.showAya(currSura, currAya, displayMode);
		} else if ( iframeEl.contentWindow ) { // IE win
				iframeEl.contentWindow.showAya(currSura, currAya, displayMode);
		}
	}

	return true;
}

//-------------------- Tafsir --------------------------

var sectId = 0 ;

function getTafsir(chapter, verse)
{
	var ajax = new AJAX();

	ajax.request("tafsir/get_tafsir.php",{chapterno:chapter,verseno:verse},getTafsirData);	
}

function getTafsirData(response)
{
	var params = response.split(':');	

	var pageid = params[0];

	var sectionid = params[1];

	getTafsirPage(currSura,pageid,sectionid);
}

function getTafsirPage(chapter, pid, sectionid)
{
	sectId = sectionid;

	var ajax = new AJAX();

	ajax.request("tafsir/show_tafsir.php",{chapterno:chapter,pageid:pid},showTafsirPage);	
}

function showTafsirPage(response)
{	
	var sura = currSura;

	var aya = currAya;

	var params = response.split(':::');

	TafsirNav = document.getElementById("TopLinks");

	TafsirNav.innerHTML = params[0];	

	TafsirPageDiv = document.getElementById("TafsirContents");

	TafsirPageDiv.innerHTML = params[1];	

	if(sectId != "-1" )
	{
		var secId = "sec_"+ sectId;

		var quranSection = document.getElementById(secId);

		quranSection.className = 'ayaHighlight';

		var scrollTafsir = new Fx.Scroll('TafsirContents', {

			wait: false,

			duration: 2500,

			offset: {'x': -100, 'y': -0},

			transition: Fx.Transitions.Quad.easeInOut

		});

		if(aya != 1)

			scrollTafsir.toElement(secId);
	}
	else 
	{
		window.scroll(0,0);
	}
	
/*
	window.addEvent('domready', function()
	{				
		// -- first example, vertical scrollbar --
		makeScrollbar( $('tafsir_contents'), $('scrollbar1'), $('handle1') );
	});
*/
}


function makeScrollbar(content,scrollbar,handle,horizontal,ignoreMouse)
{
	var steps = (horizontal?(content.getScrollSize().x - content.getSize().x):(content.getScrollSize().y - content.getSize().y))
	var slider = new Slider(scrollbar, handle, {	
		steps: steps,
		mode: (horizontal?'horizontal':'vertical'),
		onChange: function(step){
		// Scrolls the content element in x or y direction.
		var x = (horizontal?step:0);
		var y = (horizontal?0:step);
		content.scrollTo(x,y);
		}
	}).set(0);
	
	if( !(ignoreMouse) ){
		// Scroll the content element when the mousewheel is used within the 
		// content or the scrollbar element.
		$$(content, scrollbar).addEvent('mousewheel', function(e){	
		e = new Event(e).stop();
		var step = slider.step - e.wheel * 30;	
		slider.set(step);					
		});
	}
	// Stops the handle dragging process when the mouse leaves the document body.
	$(document.body).addEvent('mouseleave',function(){slider.drag.stop()});
}
						
			


function ScrollToElement(theElement)
{
  var selectedPosX = 0;

  var selectedPosY = 0;

  while(theElement != null)
  {
    selectedPosX += theElement.offsetLeft;

    selectedPosY += theElement.offsetTop;

    theElement = theElement.offsetParent;

  }

  window.scrollTo(selectedPosX,selectedPosY);
}

