var fullAccess = false;
var collectionAccess = false;
var collectionId = 0;
var loggedin = false;

// misc voxbiblia functions
// functions related to the login box at the generic header

function switchPassword(input)
{
    if (input.type == 'text') {
       var password = document.createElement('input');
       password.name = input.name;
       password.id = input.id;
       password.type = 'password';
       //password.className = input.className;
       input.parentNode.insertBefore(password,input);
       input.parentNode.removeChild(input);
       password.value = '';
       password.focus();
    }
}

var verifyPending;

/* function setPending()
 * {
 *     verifyPending = "true";
 * }
 */

function validateLogin(responseText)
{
    if(responseText.indexOf("verifyPending") != -1) {
		//AlertBox('verify_pending');
		init_popupWindow( '/static/dialogs/verify_pending.html', 450, 200, '' );
    } else if (responseText.indexOf("<input") != -1) {
        //AlertBox('login_failed');
		init_popupWindow( '/static/dialogs/login_failed.html', 450, 200, '' );
    }
}


function loginFormSubmit(form, request)
{
    var validate = function(request) {
        validateLogin( request.responseText );
    }
	
    new Ajax.Updater('login', '/login', {
		parameters:Form.serialize(form),
        onComplete: validate,
		evalScripts: true
    });

    return false;
}

function logout(compact)
{
    var params = "compactLogin=" + compact;
    new Ajax.Updater('login', '/logout', {
		evalScripts: true,
        parameters: params
    });
    return false;
}

function setUserDetails()
{
    new Ajax.Request('/userdetails');
    //new Ajax.Updater('user_details', '/userdetails', {evalScripts: true});
    return false;
}

function getStates(countryId)
{
    new Ajax.Updater('states', '/userdetails/country/' + countryId, {
		evalScripts: true
	});
    return false;
}

// bible browser functionality

// bible gets set to false here, and to true in bible.vm, that way
// we can test for bible in the javascript that's run when logging in.
var bible = false;
var collection = false;

/* Added a view param. Use it to select velocity template for rendering. */
function showSegments(chapterId,selectView)
{
    if (chapterId == -1) {
        chapterId = lastChapterId;
    }
    if (chapterId == -1) {
        // showSegents() gets called on login
        return;
    }
    var params = (selectView) ? {chapter: chapterId, view: selectView} : {chapter: chapterId};
    var controller = (creatingAlbum) ? 'createalbum' : 'bible';
    
    new Ajax.Updater('archive_col3_wrapper', '/' + controller + '/segments', {
    	parameters: params,
		evalScripts: true
	});
	
	updateSelected('chapter_' + chapterId);
    lastChapterId = chapterId;
    return false;
}


function showChapters(bookId) {
	
    new Ajax.Updater('archive_col3_wrapper', '/bible/segments?book=' + bookId, {
		evalScripts: true
	});
	
    updateSelectedBook('book_' + bookId);
    lastBookId = bookId;
    lastChapterId = -1;
    return false;
}

function showChaptersSegments(bookId) {

    var controller = 'bible';
    
    if(creatingAlbum)
    {
        controller = 'createalbum';
    }

    new Ajax.Updater('archive_col23_wrapper', '/' + controller + '?view=fragments/chapters_segments&book=' + bookId, {
        evalScripts: true
    });
	
    updateSelected('book_' + bookId);
    lastBookId = bookId;
    lastChapterId = -1;
    return false;
}

function showCollection(collectionId)
{
    new Ajax.Updater('archive_collection_wrapper', '/collections/c?collectionId=' + collectionId, {
		evalScripts: true
	});
	
    updateSelectedCollection("collection_" + collectionId);
    return false;
}

function updateSelectedCollection(collectionElementId)
{
    if (selectedCollection != collectionElementId) {
        $(selectedCollection).className = '';
    }
    selectedCollection = collectionElementId;
    $(collectionElementId).className = 'selected';
}

function debug(message)
{
    //console.log(message)
}

function updateSelectedBook(bookElementId)
{
    if (selectedBook != "" && bookElementId != selectedBook) {
        $(selectedBook).className = '';
    }
    selectedBook = bookElementId;
    $(bookElementId).className = 'selected';
}

function updateSelected(newId)
{
    var e = $(newId)
    if (e == null) {
        return
    }

    for (var i = 0; i < e.siblings().length; i++) {
        var sibling = e.siblings()[i]
        if (sibling.className == "selected") {
            sibling.className = ""
            break
        }
    }
    e.className = 'selected';
}

function updateChapterColumn(chapters)
{
    var parent = $("archive_col2");
    parent.innerHTML = "";

    for (i = 0; i < chapters.length; i++) {
        var chapter = chapters[i];

        var a = document.createElement('a');
        a.chapterId = chapter.cid;
        a.appendChild(document.createTextNode(chapter.n));
        a.onclick = function() { return showSegments(this.chapterId); };
        //a.setAttribute("onclick", "return showSegments(" + chapter.chapterId + ")");
        a.setAttribute("id", "chapter_" + chapter.cid);
        parent.appendChild(a);
    }
}

function updateAccessCount()
{
    //console.log("calling updateAccessCount");
    if (accessCount == 0) {
        setMessage(accNoDownloads);
        setDlClass("button_dl_disabled");
    } else {
        setMessage(accDownloadsLeft.replace("%d", accessCount));
    }
}

function playBook(enable)
{
    alert(enable)
    if (!enable) {
      return
    }
    return play("/player/b/" + bookId, true);
}

function playCollection()
{
    return play("/player/c/" + collectionId, true);
}

function playSegment(segmentId)
{
    return play("/player/s/" + segmentId + "/segmentId.mp3", false);
}

var playlistWindowParams = "left=0,screenX=0,top=0,screenY=0,height=350," +
          "innerHeight=350,width=500,innerWidth=500,resizable=yes,scrollbars=1"

var segmentWindowParams = "left=0,screenX=0,top=0,screenY=0,height=210," +
          "innerHeight=210,width=500,innerWidth=500,resizable=yes,scrollbars=1"

// removed to make ads meaningful at all: "scrollbars=no,resizable=no"


function playSample()
{
    var player = window.open("/player/sample", "voxplayer", playlistWindowParams)
    if (player==null || typeof(player)=="undefined") {
        AlertBox('popup_disabled')
    } else {
        player.focus()
    }
    return false
}

function displayEmbed(path, enabled)
{
    if (enabled) {
		window.open("/embedinfo" + path, "embedInfo", segmentWindowParams)        
    } else {
        var toPulsate = $('msg_container');
        if (!toPulsate) {
            toPulsate = $('login_wrapper');
        }
        new Effect.Pulsate(toPulsate, {pulses: 3, duration: 1});
    }
}

function play(url, isList)
{
    return openwWindowOrPulsate(url, "voxplayer", isList)
}

function openwWindowOrPulsate(url, windowName, isList)
{
    if (doPlay) {

		var player = window.open(url, windowName, isList ? playlistWindowParams : segmentWindowParams)
        
		if(! player || typeof(player) == "undefined" )
		   init_popupWindow( '/static/dialogs/player_unavailable.html', 450, 200, '' );
        else
           player.focus()
		
    } else {
        var toPulsate = $('msg_container');
        if (!toPulsate) {
            toPulsate = $('login_wrapper');
        }
        new Effect.Pulsate(toPulsate, {pulses: 3, duration: 1});
    }
    return false;
}

function downloadBook(enabled)
{
    return dl("/dl/b/" + bookId + "/2/book.zip", enabled);    
}

function downloadCollection()
{
    return dl("/dl/c/" + collectionId + "/2/collection.zip", true);
}

function downloadSegment(segmentId, enabled)
{
    return dl("/dl/s/" + segmentId + "/2/bible.mp3", enabled);
}

function dl(url, enabled)
{
    if (enabled) {
        window.location = url;
    }
    /*
    if (fullAccess) {
        window.location = url;
        return false;
    }

    if (window.bookId != undefined) {
        if (inArray(bookAccess, bookId)) {
            window.location = url;
            return false;
        }
    }

    if (window.collectionId != undefined) {
        if (inArray(collectionAccess, collectionId)) {
            window.location = url;
            return false;            
        }
    }

    // access of type COUNTED_DOWNLOADS shouldn't give book download access.
    if (url.indexOf("/dl/b/") == 0) {
        AlertBox("buy_archive");
        return false;
    }
    if (accessCount > 0) {
        accessCount--;
        updateAccessCount();
        window.location = url;
        return false;
    }
    AlertBox('buy_archive');
    return false;
      */
}

/*
function updateCollectionDl()
{
    if (fullAccess) {
        setDlClass("button_dl");
        $("book_dl").className = "button_dl";
    } else if(inArray(bookAccess, bookId)) {
        accMessage = "Du har tillgång till denna bok";
        //console.log("in book case");
        setDlClass("button_dl");
        $("book_dl").className = "button_dl";
    }  else if (accessCount > 0) {
        setDlClass("button_dl");
    }
}
*/

function updateDl()
{
    if (fullAccess) {
        setDlClass("button_dl");
        $("book_dl").className = "button_dl";
    } else if(inArray(bookAccess, bookId)) {
        accMessage = "Du har tillgång till denna bok";
        //console.log("in book case");
        setDlClass("button_dl");
        $("book_dl").className = "button_dl";
    } else if (accessCount > 0) {
        setDlClass("button_dl");
        $("book_dl").className = "button_dl_disabled"
    }
}

var accMessage;
var loginAjaxAddons = []

function loginHook(ajax)
{
    togglePlay(true);
    doPlay = true;
    if (window.collectionId != undefined) {
        updateCollectionDl();
    } else if (window.bookId != undefined) {
        updateBookDl();
        setMessage(accMessage);
    }
    if (ajax) {  
        for (i = 0 ; i < loginAjaxAddons.length; i++) {
            loginAjaxAddons[i]();
        }
    }
}

function logoutHook()
{
    togglePlay(false);
    setDlClass("button_dl_disabled");
    setMessage(accMessage);
    doPlay = false;
    if (window.collectionId != undefined) {
        toggleCollectionAccess(false);
    } else {
        e = $("book_dl");
        if (e) {
            e.className = "button_dl_disabled";
        }
    }
}

function updateCollectionDl()
{
    if (fullAccess) {
        setDlClass("button_dl");
        toggleCollectionAccess(true);
    } else if(inArray(collectionAccess, collectionId)) {
        //accMessage = "Du har tillgång till denna samling";
        //console.log("in book case");
        setDlClass("button_dl");
        toggleCollectionAccess(true);
    } 
}


function updateBookDl()
{
    if (fullAccess) {
        setDlClass("button_dl");
        $("book_dl").className = "button_dl";
    } else if(inArray(bookAccess, bookId)) {
        accMessage = "Du har tillg&aring;ng till denna bok";
        //console.log("in book case");
        setDlClass("button_dl");
        $("book_dl").className = "button_dl";
    } else if (accessCount > 0) {
        setDlClass("button_dl");
    }
}

function inArray(array, element)
{
    for (i = 0 ; i < array.length; i++) {
        if (array[i] == element) {
            return true;
        }
    }
    return false;
}


function buy()
{
    AlertBox("buy_archive");
}

function flashLogin()
{
    new Effect.Shake('login_wrapper', { duration: 1});
    return false;
}

function setMessage(text)
{
    var msgContainer = $("msg_container");
    if(msgContainer) {
        msgContainer.innerHTML = text;
    }
}

function togglePlay(enable)
{
    var className = 'button_play_disabled'
    var embedClass = 'button_embed_disabled'
    if (enable) {
        className = 'button_play'
        embedClass = 'button_embed'
    }

    var divs = document.getElementsByClassName("play_marker");
    for (i = 0; i < divs.length; i++) {
        divs[i].className = "play_marker " + className;
    }
    divs = document.getElementsByClassName("embed_marker")
    for (i = 0; i < divs.length; i++) {
        divs[i].className = "embed_marker " + embedClass        
    }
}


function setDlClass(className)
{
    var divs = document.getElementsByClassName("dl_marker");
    for (i = 0; i < divs.length; i++) {
        divs[i].className = "dl_marker " + className;
    }
}

var onLoaders = [];

function bibleOnLoadHook()
{
    for (var i = 0; i < onLoaders.length; i++) {
        onLoaders[i]();
    }
}

function selectBook( version, testament, trigger ) {	

    var ver = ""

    if ($("choose_bible")) {
        ver = "&=v" + $("choose_bible").value
    }
	if( location.toString().indexOf("/album") != -1 ) {
		document.location = "/bible?t=" + testament + ver
	}
	else if( location.toString().indexOf("/search") != -1 || location.toString().indexOf("/text") != -1 ) {
		
		if( trigger ) {
			$(trigger).siblings().invoke("removeClassName","selected");
			$(trigger).addClassName( "selected" );
		}
			
		$("testament").value = testament;
	}
	else {
		var controller = "/bible";
		if( location.toString().indexOf("/createalbum") != -1 ) {
		    controller = "/createalbum";
		}
		
		new Ajax.Updater('book_view', controller + '?view=fragments/archive'
			+ '&version=' + version
			+ '&t=' + testament, {
					evalScripts: true
		});
	
		if( trigger ) {
			$(trigger).siblings().invoke("removeClassName","selected");
			$(trigger).addClassName( "selected" );
		}
		
		selected_version = version;
		selected_testament = testament;
		return false;
	}
		

}

// Create album functions

function modifyPlaylist(action, segmentId)
{
    var param;
	
    if(action == 'add' || action == 'remove' || action == 'up' || action == 'down') {
        param = action;
    }

    new Ajax.Updater('create_album_playlist_holder', '/createalbum?view=fragments/createAlbumPlaylist&' + param + '=' + segmentId, {
        evalScripts: true
    });
    
    return false;
}


function saveAlbum(form)
{
    new Ajax.Updater('create_album_settings_holder', '/createalbum?view=fragments/createAlbumSettings&save=save', {
    	evalScripts: true,
        parameters: Form.serialize(form),
        onComplete: function() { setTimeout("saveAlbumCompleted()", 20) }   // allow the evalScripts to run before we run the callback.
    });
    
    $('logo').scrollTo();
    
    return false;
}

function saveReadingList(form)
{
    new Ajax.Updater('create_reading_list_settings_holder', '/readinglist?action=save', {
    	evalScripts: true,
        parameters: Form.serialize(form)
    });

    $('logo').scrollTo();

    return false;
}

function selectThis(name)
{
    $('create_album_settings_image').innerHTML =  '<input type="hidden" name="selected_image" value="' + name + '" />'
                                                + '<a href="#" onclick="return init_popupWindow( \'/imageselector\', 750, 650, \'\' );">'
                                                + '<img src="/static/img/album_page/icons/small/' + name + '.jpg"/></a>';
    closePopup();
}

function saveAlbumCompleted()
{
    if(saveAlbumSuccess()) {
        init_popupWindow("/static/dialogs/" + lang + "/album_saved.html", 450, 200, "");
    }
}

function uploadImage(formId)
{
	alert('upload function entered');
    document.getElementById(formId).submit();  
    // closePopup();
         
	return false;
}


// MyPage functions

function toggleElement(elementId)
{
    if($(elementId).visible())
        Effect.BlindUp(elementId);
    else
        Effect.BlindDown(elementId);
    
    return false;
}

function changePasswordSubmit(formId)
{
	new Ajax.Updater('mypage_change_password_holder', '/mypage?view=changePasswordForm&save=save', {
        evalScripts: true,
        parameters: Form.serialize(formId)
    });
	
	return false;
}

function changeDisplayNameSubmit(formId)
{
    new Ajax.Updater('mypage_change_display_name', '/mypage?view=changeDisplayNameForm&save=save', {
        evalScripts: true,
        parameters: Form.serialize(formId)
    });
    
    return false;
}

function changeNameSubmit(formId)
{
    new Ajax.Updater('mypage_change_name', '/mypage?view=changeNameForm&save=save', {
        evalScripts: true,
        parameters: Form.serialize(formId)
    });
    
    return false;
}

function displayAlbumList(controller, holder, page, extra)
{
	if(extra == undefined)
		extra = '';
		
	new Ajax.Updater(holder, controller + '?view=albumList&page=' + page + extra);
	
	return false;
}

// Search and reading list related
function performAjaxSearch(searchString)
{
	if ($("search_form") == undefined)
	{
	   new Ajax.Updater('search_container','/search?ajax=true');
	}
	else
	{
	   new Ajax.Updater('search_container','/search?ajax=true', {
		                  parameters:Form.serialize('search_form'),
	                       method: 'post'
	                    });
	}
	
	return false;
}

function addToReadingList(element, book, startChapter, beginVerse, stopChapter, endVerse)
{
    var endStop = ""
    if (stopChapter != null) {
        endStop = "&stopChapter="+ stopChapter + "&endVerse=" + endVerse
    }
    var f = function (){element.innerHTML='Added'}
    new Ajax.Updater('reading_list_verse_holder',
            '/readinglist?action=displayList&operation=add&book=' + book +
            '&startChapter='+ startChapter  + '&beginVerse=' + beginVerse +
            endStop,{onComplete: f})
    return false;
}

// position is 1-based, because of the builtin velocityCount variable
function modifyReadingList(action, position)
{
    if (action == "remove" || action == "up" || action == "down") {
        new Ajax.Updater('reading_list_verse_holder', '/readinglist?' +
                 'action=displayList&operation='+action+'&position='+position)
    }
    return false;
}



function toggleReadingListMode()
{
	$$("div.reading_list_verse").each( function(verse) { verse.toggleClassName("compact") } );

	return false;
}


// collections page functions

function toggleCollectionAccess(enable)
{
    var btns = "none";
    var buy = "inline";
	
    if (enable) {
        btns = "inline";
        buy = "none";
    }

   
    if( $("collection_btns") )
        e.style.display = btns;
    
	if( $("collection_buy") )
        e.style.display = buy;

}

function onBibleVersionChange(bibleVersion)
{
    selected_version = bibleVersion
        if (bibleVersion == ''){
            return
        }
        var url = window.location.href
        url = stripPreviousVersion(url)
        if (url.indexOf('?') != -1) {
            url = url + "&version=" + bibleVersion
        } else {
            url = url + "?version=" + bibleVersion
        }
        window.location = url

}

function stripPreviousVersion(url)
{
    var i = url.indexOf('version=')
    if (i != -1) {
        url =  url.substr(0, i - 1)
    }
    return url
}

function clickedCreateAlbum(lang)
{
    if (loggedin) {
        window.location = "/createalbum"
        return false;
    } else {
        return init_popupWindow( '/static/dialogs/' + lang + '/not_logged_in.html', 450, 200, '' )
    }
}

function clickedCreateReadingList(lang)
{
    if (loggedin) {
        window.location = "/readinglist?create"
        return false;
    } else {
        return init_popupWindow( '/static/dialogs/' + lang + '/not_logged_in.html', 450, 200, '' )
    }
}


function onLegendPlay()
{
	q=document.getElementsByClassName("button_play")
	q=q.concat(document.getElementsByClassName("play"))
	for (i = 0; i < q.length; i++) {
		if (q[i]!=$('key_container_play')) {
			new Effect.Pulsate (q[i], {pulses: 2, duration: 0.3})
		}
	}
}

function onLegendDownload()
{
	q=document.getElementsByClassName("button_dl")
	q=q.concat(document.getElementsByClassName("download"))
	for (i = 0; i < q.length; i++) {
		if (q[i]!=$('key_container_download')) {
			new Effect.Pulsate (q[i], {pulses: 2, duration: 0.3})
		}
	}
}

function onLegendEmbed()
{
	q=document.getElementsByClassName("button_embed")
	for (i = 0; i < q.length; i++) {
		if (q[i]!=$('key_container_embed')) {
			new Effect.Pulsate (q[i], {pulses: 2, duration: 0.3})
		}
	}
}

var verseVisibilitySavedText

// the reason this function toys around with UI strings as parameters is because
// the js files are static and doesn't handle multiple languages, so we bring
// that from the views
function toggleVerseVisibility(otherText, element)
{
    if (verseVisibilitySavedText == null) {
        verseVisibilitySavedText = otherText
    }
    var curText = element.innerHTML
    element.innerHTML = verseVisibilitySavedText
    verseVisibilitySavedText = curText

    q = document.getElementsByClassName("id_column_read")
    for (i = 0; i < q.length; i++) {
        if (q[i].style.display == "none") {
            q[i].style.display = "inline"
        } else {
            q[i].style.display = "none"
        }
    }
    return false
}

function displayPrint(rlId)
{
    var e = document.getElementsByClassName("id_column_read")[0]

    var verses = e.style.display == "none" ? "no" : "yes"

    var w = window.open(
            "/readinglist?action=printView&rlId=" + rlId +
            "&versenumbers="  + verses);

    if (w != null) {
        w.focus()
    }


    return false
}

function searchLink(url, ajax)
{
    if (ajax) {
        if (url.indexOf('?') != -1) {
            url = url + "&ajax=true"
        } else {
            url = url + "?ajax=true"
        }
        new Ajax.Updater('search_container', url)
    } else {
        window.location = url
    }
    return false;
}
