var popupVisible = false;
var cartChanged = false;

// Ugly fix for FireFox > 2 to solve the lack of support of the W3C supported display:inline-block;

function interface_bugFix() { 

	if( navigator.userAgent.indexOf("Firefox") != -1 ) {
		var e = $("cart_count")
		if (e != null) {
			e.style.display = "-moz-inline-block";
		}
	}
	
	if( navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Safari") != -1 ) {
		var album_container = $("album_container");
		var footer_container = $("footer_container");
		if( album_container && footer_container ) {
			album_container.style.height = ( findPosY( footer_container ) - 245 ) + "px";
		}
	}
	
}

function findPosY(obj) {
    var curtop = 0;
    if(obj.offsetParent)
        while(1) {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

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;
	pW_content_obj_top = ( get_clientHeight() - get_styleMeasurementsToInt( pW_content_obj.style.height ) ) / 2;
	
	if( pW_content_obj_left < 20 )
		pW_content_obj_left = 20;
		
	if( pW_content_obj_top < 20 )
		pW_content_obj_top = 20;
	
	pW_content_obj.style.left = pW_content_obj_left + "px"
	pW_content_obj.style.top = pW_content_obj_top + "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 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", "" ) );
	
}

// Ajax

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

}

// Used to trigger browser specific functions

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

function getVariantId(productId, prefix)
{
    var singleInput = $("single_variant_" + productId)
    if (singleInput != null) {
        return singleInput.value
    } 
    var radios = document.forms[prefix + productId]["type_" + productId]
    for (var i = 0; i < radios.length; i++) {
        if (radios[i].checked) {
            return radios[i].value
        }
    }
}

/**
 * Make cart visible blinking once.
 */
function addToCart(productId, prefix, view)
{
    var params = "pid="+  productId + "&bibleVersionId=" + 
    				 getVariantId(productId, prefix)


    new Ajax.Updater('compact_cart_container', '/store/cart', {
		parameters: params,
		onComplete: function() {
			afterCartAdded(view);
			interface_bugFix();
		}
	});
    return false;
}

function addAlbumToCart(albumId)
{
    var params = "albumId=" +  albumId + "&action=addToCart"

    new Ajax.Updater('compact_cart_container', '/albums', {
		parameters: params,
		onComplete: function() {
			afterCartAdded();
			interface_bugFix();
		}
	});
    return false;
}


function addProductToCart(productId, bibleVersionId)
{
    var params = "pid=" +  productId + "&bibleVersionId=" + bibleVersionId

    new Ajax.Updater('compact_cart_container', '/store/cart', {
		parameters: params,
		onComplete: function() {
			afterCartAdded();
			interface_bugFix();
		}
	});
    return false;
}

function addBookToCart(bookId)
{
    var params = "bookId=" + bookId

    new Ajax.Updater('compact_cart_container', '/store/cart', {
		parameters: params,
		onComplete: function() {
			afterCartAdded();
			interface_bugFix();
		}
	});
    return false;
}


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 init_cartMessage() {
	return init_popupWindow( '/info/generic/cart_add', 450, 200, '' );
}

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 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 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
    }
}

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"
    }
}

function closePopup()
{
    return close_popUpWindow('popup_container,popup_background_container')
}

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

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

function init_discount() {
	
	var discount_code = $("discount_code")
	var discount_message = $("discount_message");
	var ok = true;
	
	if( ok ) {
		 discount_message.innerHTML = "<b>Rabatten har dragits av i varukorgen!</b> Vill du l�sa in fler rabatter kan du g�ra det i f�ltet till h�ger.";
		 new Effect.Pulsate( 'discount_message', { pulses: 1, duration: 0.7 } );
	}
	
	return false;
	
}

function init_topMenuSelection() {

	// Highlights correct top menu objects due to values passed by query string
	
	var location_search = location.search;
	
	if( location_search ) {	
		
		var query_vars_arr = location_search.toQueryParams();
		
		if( query_vars_arr['v'] )
			$("choose_bible").value = query_vars_arr['v'];
			
		if( query_vars_arr['t'] && query_vars_arr['v'] )
			selectBook( query_vars_arr['v'], query_vars_arr['t'], $("button_" + query_vars_arr['t']) )
			
	}

}

//	Init onload events

interface_bugFix();
init_topMenuSelection();