/*
 * This file is an attempt to clean up the sort of unstructured javascript
 * content from alert_box.js, effects.js, embeddedcontent.js, format.js,
 * interface.js, login.js, vox2.js and voxbiblia.js. This file contains
 * copies of functions actually used in all or most pages and should be used
 * for new pages.
 */

/*
 * login and logout functionality
 */
function loginFormSubmit(form)
{
    var validate = function(request) {
        validateLogin(request.responseText);
    }

    new Ajax.Updater('login', '/login', {
		parameters: Form.serialize(form),
        onComplete: validate,
		evalScripts: true
    });

    return false;
}

function logout()
{
    new Ajax.Updater('login', '/logout', { evalScripts: true });
    return false;
}

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();
    }
}

function submitReminder(form, targetId)
{
    new Ajax.Updater(targetId, '/reminder',
            {parameters:Form.serialize(form)});
    return false;
}

/*
 * shopping cart functionality
 */

function checkOut(secure, useHttps)
{
    if (!secure && useHttps) {
        var e = $('cartRedirectMessage')
        e.className = "cart_redirect"
        e.style.display = "block"
        var s = document.location.href.replace("http://", "https://")
        if (s.indexOf("?") == -1) {
            s = s + "?checkout=yes"
        } else {
            s = s + "&checkout=yes"
        }
        document.location = s
        return false
    } else {
        return init_popupWindow('/store/check_out', 680, 680, '');
    }
}

function afterCartAdded(view)
{
    if( popupVisible && view ) {
        new Ajax.Updater('detail_compact_cart_container', '/store/cart?view='+view,
            {onComplete: flashCart})
    }
    flashCart();
	if (!popupVisible)
		init_cartMessage();
}


function flashCart()
{
    new Effect.Appear('compact_cart_container',{duration: 0.2})
    new Effect.Pulsate('compact_cart_container',{pulses: 1, duration: 0.7})
    if (popupVisible) {
        new Effect.Appear('detail_compact_cart_container',{duration: 0.2})
        new Effect.Pulsate('detail_compact_cart_container',{pulses: 1, duration: 0.7})
    }
}


function removeCartItem(ordinal)
{
    new Ajax.Updater("extended_cart_container", "/store/extended_cart",
       {parameters: "n=" +ordinal})
    cartChanged = true
    return false
}


function showDetails(productId)
{		init_popupWindow('store/product_info', 680, 680,
               "pid=" + productId + "&bibleVersionId=" +
               getVariantId(productId, "f_"))
}

function updatePrice(newPrice)
{
    $('price_container').innerHTML = newPrice;
}

function debug(msg)
{
    if (window.console  != null) {
        console.log(msg)
    }
}

function disableSubmit()
{
    //debug("calling disableSubmit()")
    $('label_next').style.display="none"
    $('label_wait').style.display="block"

}

function enableSubmit()
{
    //debug("calling enableSubmit()")
    $('label_wait').style.display="none"
    $('label_next').style.display="block"
}


function removeErrors()
{
    doRemoveErrors("orderForm")
    doRemoveErrors("card_information")
    doRemoveErrors("address_spacer")
    var e = $("accept_label")
    if (e != null) {
        e.className = ""
    }
}

function displayOrderLogin(params)
{
    if (params == null) {
        params = ""
    }
    new Ajax.Updater("form_container", "/store/order_login", {evalScripts: true,
        parameters: params})
}


function doRemoveErrors(parentId)
{
    var form = $(parentId)
    if (form == null) {
        return
    }
    var e = $("error_msg")
    if (e != null) {
        $("error_msg").style.display="none"
    }
    for (var i = 0; i < form.childNodes.length; i++) {
        var child = form.childNodes[i]
        if (child == null || child.nodeType != 1) {
            continue;
        }
        if (child.className = "error") {
            child.className = ""
        }
        child.onfocus = null
        child.onblur = null
    }
}

function acceptClick()
{
    var a = $("accept")
    if (a == null) {
        return
    }
    a.value = $('accept_trigger').checked ? "on" : ""
}


var eulaOK = false

function evalDebug(response)
{
    try {
        eval(response.responseText)
    } catch(e) {
        debug(e)
    }

}

var doLogin = false

function handleNext(form)
{
    if (doLogin) {
        new Ajax.Request("/store/login_submit", {parameters:Form.serialize(form),
          onSuccess: evalDebug
          })
        return;
    }

    if (needsEULA && !eulaOK) {
        Effect.toggle('license','blind')
    } else {
        removeErrors()
        disableSubmit()
        new Ajax.Request('/store/order_submit', {parameters:Form.serialize(form),
            onSuccess: function(response) {
                evalDebug(response)
                enableSubmit()
         }, onFailure: function(response) {
            $("page_container").innerHTML = response.responseText
            closePopup()
        }})
    }
}

function displayFormError(msg)
{
    var e = document.getElementById("error_msg")
    if (e == null) {
       return
    }
    if (msg != null) {
        e.innerHTML = msg
    }
    e.style.display = "block"
}

function displayErrorFactory(msg)
{
    return function() {
        displayFormError(msg)
    }
}

function onCountryChange(otherCountryId)
{
    var e = $("countryId")
    var selectedId = e.options[e.selectedIndex].value
    if (selectedId == otherCountryId) {
        $("other_country").style.display = "inline"
        $("other_country_label").style.display = "inline"
    } else {
        $("other_country_label").style.display = "none"
        $("other_country").style.display = "none"
    }
}


/*
 * Low level popup window stuff
 */
function closePopup()
{
    return close_popUpWindow('popup_container,popup_background_container')
}


function init_popupWindow( pW_contentUrl, pW_width, pW_height, params ) {

	if( $('popup_container') && $('popup_background_container') )
		close_popUpWindow( 'popup_container,popup_background_container' );

	if( !pW_background_obj || !pW_content_obj ) {

		// Background layer

		var	pW_background_obj = null;
			pW_background_obj = document.createElement("div");
			pW_background_obj.id = "popup_background_container";
			pW_background_obj.style.display = "none";

		document.body.appendChild( pW_background_obj );


		// Content layer

		var	pW_content_obj = null;
			pW_content_obj = document.createElement("div");
			pW_content_obj.id = "popup_container";
			pW_content_obj.style.display = "none";

		// Load the content of the layer

		load_popupWindow_content( pW_content_obj, pW_contentUrl, params);

		document.body.appendChild( pW_content_obj );
		popupVisible = true;
	}

	// Set specified measurements, otherwise set to css default

	if( pW_width )
		pW_content_obj.style.width = pW_width + "px";
	else
		pW_content_obj.style.width = "500px";

	if( pW_height )
		pW_content_obj.style.height = pW_height + "px";
	else
		pW_content_obj.style.height = "500px";

	// Set the position of the content layer

	pW_content_obj_left = ( get_clientWidth() - get_styleMeasurementsToInt( pW_content_obj.style.width ) ) / 2;


	if( pW_content_obj_left < 20 )
		pW_content_obj_left = 20;


	pW_content_obj.style.left = pW_content_obj_left + "px"

	// Show the layers

	new Effect.Appear( pW_background_obj, { duration: .3, from: .0, to: .8 } );
	new Effect.Appear( pW_content_obj, { duration: .3 } );

	// Ugly fix for FireFox > 2 to solve scrollbar bug
	// reset by close_popUpWindow function

	if( navigator.userAgent.indexOf("Firefox") != -1 ) {
		if( $("archive_col1") )
			$("archive_col1").style.overflow = "hidden";

		if( $("archive_col2") )
			$("archive_col2").style.overflow = "hidden";
	}

	// Ugly fix for IE6 to solve problem with select menu bug
	// reset by close_popUpWindow function

	if( navigator.userAgent.indexOf("MSIE 6") != -1 )
		$(choose_bible).style.visibility = "hidden";

	return false;

}

function close_popUpWindow( window_list ) {

	// Accepts ether list of windows separeted by "," or singel id referense

	if( window_list.indexOf(",") != -1 ) {
		window_list.split( "," ).each( Element.remove );
	}
	else {
		Element.hide( window_list );
	}

    if( cartChanged ) {
        new Ajax.Updater("compact_cart_container", "/store/cart", {
			evalScripts: true
		});
        cartChanged = false
    }

	// Resets ugly fix for FireFox > 2 to solve scrollbar bug

	if( navigator.userAgent.indexOf("Firefox") != -1 ) {
		if( $("archive_col1") )
			$("archive_col1").style.overflow = "auto";

		if( $("archive_col2") )
			$("archive_col2").style.overflow = "auto";
	}

	// Resets ugly fix for IE6 to solve problem with select menu bug

	if( navigator.userAgent.indexOf("MSIE 6") != -1 )
		$(choose_bible).style.visibility = "visible";


    popupVisible = false;
    return false;

}

function load_popupWindow_content( container, content_url, params ) {

	new Ajax.Updater( container, content_url, {
		evalScripts: true,
		parameters: params,
		onComplete: init_browserFunctions
    })

}

function init_browserFunctions() {
	if( init_pngFix )
		init_pngFix();
}

function get_clientWidth() {

	return document.body.clientWidth ? document.body.clientWidth : window.innerWidth;

}

function get_clientHeight() {

	return document.body.clientHeight ? document.body.clientHeight : window.innerHeight;

}

function get_styleMeasurementsToInt( string ) {

	return parseInt( string.replace( "px", "" ) );

}

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
}