
function launchwin( winUrl, winName, winFeatures ) {
    newWin = window.open( winUrl, winName, winFeatures+',scrollbars=yes,resizable=yes' );
}


function partiallySubmitOrderForm() {
    document.orderShipmentForm.partialSubmission.value = "true";
    document.orderShipmentForm.submit();
}

function partiallySubmitOrderPickupForm() {
    document.orderPickupForm.partialSubmission.value = "true";
    document.orderPickupForm.submit();
}

function partiallySubmitQuickBuyForm() {
    document.quickBuyForm.partialSubmission.value = "true";
    document.quickBuyForm.submit();
}

function confirmLoad( theUrl ) {
    if( confirm( 'Sind Sie sicher?' ) ) {
        location.href = theUrl;
    }
}

function openNewsletter(url) {
	var name = "newsletter";
	var features = "toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=660,height=720,top=60,left=100";
	newwin = window.open(url,name,features);
}

function toggleExplanation( obj ) {
    x = document.getElementById( obj );
    if( x.style.display != 'none' ) {
        x.style.display = 'none';
    } else {
        x.style.display='block';
    }
}

function addSearch( urlNr, affiliateName ) {
    if ((typeof window.sidebar == 'object') && (typeof window.sidebar.addSearchEngine == 'function')) {
        window.sidebar.addSearchEngine(
            'https://images.libri.de/shop/logos/mozsearch/' + urlNr + '.src',
            'https://images.libri.de/shop/logos/mozsearch/' + urlNr + '.png',
            affiliateName,
            'Bücher'
            /*'http://www.libri.de/shop/action/shop/addmozsearch/?urlnr='+urlNr,
            'http://images.libri.de/shop/searchengine/'+urlNr+'.png',
            'Libri.de',
            'Bücher'*/
        );
    } else {
        alert('Mozilla M15 or later is required to add a search engine.');
    }
}

function isMoz() {
    if ((typeof window.sidebar == 'object') && (typeof window.sidebar.addSearchEngine == 'function')) {
        return true;
    }
    return false;
}

function openWindowCenter( url, name, width, height ) {
    var winX = (screen.width - width) / 2;
    var winY = (screen.height - height) / 2;
    windowProperties = 'width=' + width + ',height=' + height + ',left=' + winX + ',top=' + winY + ',scrollbars=no,resizable';
    newwin = window.open( url, name, windowProperties );
}

function OpenPopUp(breite,hoehe,Ziel) {
    OpenPopUpName(breite,hoehe,'PopUp',Ziel)
}

function OpenPopUpName(breite,hoehe,pop_name,Ziel) {
    OpenPopUpNamePara(breite,hoehe,pop_name,'',Ziel);
}

function OpenPopUpNamePara(breite,hoehe,pop_name,para,Ziel) {
    var fc_js_pos = getCenterPosition(breite,hoehe);
    
    var options ="width="+breite+",height="+hoehe+",toolbar=no,locationbar=no,directories=no,scrollbars=auto,status=no,menubar=no,resizable=no"+fc_js_pos;
    if (para == 'scroll') {
        options ="width="+breite+",height="+hoehe+",toolbar=no,locationbar=no,directories=no,scrollbars=yes,status=no,menubar=no,resizable=no"+fc_js_pos;
    }
    if (para == 'noscroll') {
        options ="width="+breite+",height="+hoehe+",toolbar=no,locationbar=no,directories=no,scrollbars=no,status=no,menubar=no,resizable=no"+fc_js_pos;
    }

    if (pop_name == ''){
        pop_name = 'Popup';
    }
    
    
    var newwindow = open(Ziel,pop_name,options);
    if (newwindow != null){
        newwindow.focus();
    }
}


function showElement( divid ) {
	var element = document.getElementById( divid );
	
	if ( element && element.style.display == 'none' ) {
		element.style.display = 'block';
	}
}

function setRating( value ) {
    var rating = document.getElementById( 'rating' );

    if ( rating ) {
        rating.value = value;
    }
    
    var ratingForm = document.getElementById( 'ratingForm' );
    if ( ratingForm ) {
        switch ( value ) {
            case 1:
            ratingForm.className = 'liRating liOnestar';
            break;
            case 2:
            ratingForm.className = 'liRating liTwostar';
            break;
            case 3:
            ratingForm.className = 'liRating liThreestar';
            break;
            case 4:
            ratingForm.className = 'liRating liFourstar';
            break;
            case 5:
            ratingForm.className = 'liRating liFivestar';
            break; 
        }
    }
        
}
    
function textCounter(field, countfield, fieldlength) {
    if (field.value.length > fieldlength) {
        alert('Ihr Text darf maximal '+fieldlength+' Zeichen lang sein.');
        field.value = field.value.substring(0, fieldlength);
        field.focus()
    }
    countfield.value = fieldlength - field.value.length;
}

function sendReview() {
    var form = document.getElementById( 'reviewForm' );
    var field = document.getElementById( 'reviewAction' );
    
    if ( form && field ) {
        field.value= 'save_login';
        form.submit();
    }
}

function initializeRating( rating ) {
            
    if ( rating && rating > 0 ) {
        setRating( rating );
    } 
}

function loadStyleSheet(filename){
          var stylesheet=document.createElement("link")
          stylesheet.setAttribute("rel", "stylesheet")
          stylesheet.setAttribute("type", "text/css")
          stylesheet.setAttribute("href", filename) 
          document.getElementsByTagName("head")[0].appendChild(stylesheet)
}
function loadScript(filename){
         var script=document.createElement('script')
          script.setAttribute("type","text/javascript")
          script.setAttribute("src", filename)
          document.getElementsByTagName("head")[0].appendChild(script)
}

function switchCategory(categoryTeaserId, index, numTabs){
	if(numTabs == null || numTabs == undefined) {
		numTabs = 3;
	}
	 for (var idx = 0; idx < numTabs ; idx++ ){
		 var categoryBox = document.getElementById( categoryTeaserId+'_'+idx);
		 var categoryHeader = document.getElementById( 'L'+categoryTeaserId+'_'+idx);
		 if (categoryHeader!=null){
			 if (idx==index){
				 //categoryHeader.setAttribute("class", "active");
				 categoryHeader.className = "active";
			 } else {
				 //categoryHeader.setAttribute("class", "inactive");
				 categoryHeader.className = "";
			 }
		 }
		 if (categoryBox!=null){
			 if (idx==index){
				 categoryBox.style.display = "block";
			 } else {
				 categoryBox.style.display = "none";
			 }
		 }
	 }
}

if ( window.libri == null ) {
    window.libri = {};
}

if ( window.libri.util == null ) {
    window.libri.util = new function() {
        var _objectToString = function( obj ) {
            var str = "{";
            for ( var prop in obj ) {
                str += prop+": "+obj[prop]+", ";
            }
            str += "}"
            return str;
        };
        return {
            "objectToString": _objectToString
        };
    }
}

var console;
if ( !console ) {
	console = {};
}
if ( !console.debug ) { console.debug = function() {} };
if ( !console.log ) { console.debug = function() {} };
if ( !console.error ) { console.debug = function() {} };


if ( window.libri.shoppingcart == null ) {
    window.libri.shoppingcart = new function() {

        var _animationSpeed = "def";
        
        var _show = function () {
            libri.bookmarklist.hide();
            //console.debug("libri.showShoppingCart called...");
            var callback = function( responseText, textStatus, XMLHttpRequest ) {
                //console.debug("libri.showShoppingCart -> callback");
                $(this).slideDown( _animationSpeed );
                $("a.shoppingCartShow").hide();
                $("a.shoppingCartHide").show();
            }; 
            $("#ajaxShoppingCart").load( 
                    "/shop/action/shoppingcart/ajax", 
                    "", // data
                    callback
            );
        };
        
        var _hide = function() {
            $("#ajaxShoppingCart").slideUp( _animationSpeed );
            $("a.shoppingCartHide").hide();
            $("a.shoppingCartShow").show();
        };
        
        var _change = function( uniqueId, inputBaseName, inputIndex ) {
            //console.debug("change called");
            var inputName = inputBaseName+"["+inputIndex+"]";
            //console.debug("change: inputName = "+inputName);
            var amount = $("#shoppingCartForm").find("[name="+inputName+"]").val();
            //console.debug("change: amount = "+amount);
            $("#ajaxShoppingCart").load( 
                    "/shop/ws/shoppingcart/changeshoppingcart",
                    "id="+uniqueId+"&amount="+amount+"&forward=/action/shoppingcart/ajax",
                    function() {
                        //console.debug("libri.shoppingcart.change callback");
                    }
            );
            
        };
        
        var _remove = function( uniqueId ) {
            //console.debug("remove: uniqueId="+uniqueId);
            if ( uniqueId != null ) {
                $("#ajaxShoppingCart").load(
                        "/shop/ws/shoppingcart/removeitem",
                        "id="+uniqueId+"&forward=/action/shoppingcart/ajax",
                        function() {
                            //console.debug("libri.shoppingcart.remove callback");
                        }
                );
            }
        }

        var _changeToSubscription = function( params ) {
            var uniqueId = params["uniqueId"];
            var subscription = params["subscription"];
            var article = params["article"];
            //console.debug("libri.shoppingcart.changeToSubscription: uniqueId="+uniqueId+", subscription="+subscription+", article="+article);
            var paramString = "id="+uniqueId;
            paramString += "&subscription="+subscription;
            paramString += "&article="+article;
            paramString += "&forward=/action/shoppingcart/ajax";
            $("#ajaxShoppingCart").load(
                    "/shop/ws/shoppingcart/changetosubscription",
                    paramString,
                    function() {
                        //console.debug("libri.shoppingcart.delete callback");
                    }
            );
        }

        var _add = function ( articleId ) {
            //console.debug("article="+articleId);
            var paramString = "article="+articleId;
            var transactionId = new Date().getTime();
            paramString += "&transaction="+transactionId;
            jQuery.getJSON( "/shop/ws/shoppingcart/addtoshoppingcart", 
                paramString,
                function( data, textStatus ) {
                    //console.debug("libri.shoppingcart.add callback: data="+libri.util.objectToString(data));
                    //console.debug("libri.shoppingcart.add callback: textStatus="+textStatus);
                    if ( data.total != null ) {
                        _setTotal( data.total );
                    }
                    if ( data.totalAmount != null ) {
                        _setTotalAmount( data.totalAmount );
                    }
                    _show();
                } );
        }
        
        var _setTotalAmount = function( totalAmount ) {
            $(".shoppingCartTotalAmount").html( totalAmount );
        	if ( totalAmount > 0 ) {
        		$("#warenkorbBoxEmpty").hide();
        		$("#warenkorbBox").show();
        	} else {
        		$("#warenkorbBox").hide();
        		$("#warenkorbBoxEmpty").show();
        	}
        }
        
        var _setTotal = function( total ) {
            $(".shoppingCartTotal").html( total );
        }
        
        return {
            "show": _show,
            "hide": _hide,
            "add": _add,
            "change": _change,
            "remove": _remove,
            "changeToSubscription": _changeToSubscription,
            "setTotalAmount": _setTotalAmount,
            "setTotal": _setTotal
        };
    }
}

if ( !window.libri.bookmarklist ) {
    window.libri.bookmarklist = (function() {

        var _animationSpeed = "def";

        var _show = function() {
            libri.shoppingcart.hide();
            //console.debug("libri.bookmarklist.show called...");
            var callback = function( responseText, textStatus, XMLHttpRequest ) {
                //console.debug("libri.bookmarklist.show -> callback");
                $(this).slideDown( _animationSpeed );
                $("a.bookmarkListShow").hide();
                $("a.bookmarkListHide").show();
            }; 
            $("#ajaxBookmarkList").load( 
                    "/shop/action/account/bookmark/list/ajax",
                    "", // data
                    callback
            );
        };

        var _hide = function() {
            $("#ajaxBookmarkList").slideUp( _animationSpeed );
            $("a.bookmarkListHide").hide();
            $("a.bookmarkListShow").show();
        }

        var _add = function( articleId ) {
            //console.debug("article="+articleId);
            var paramString = "article="+articleId;
            jQuery.getJSON( "/shop/ws/bookmarklist/add", 
                paramString,
                function( data, textStatus ) {
                    //console.debug("libri.bookmarklist.add callback: data="+libri.util.objectToString(data));
                    //console.debug("libri.bookmarklist.add callback: textStatus="+textStatus);
                    $("a.addBookmark.article_"+articleId).hide();
                    _show();
                } );

        }

        var _remove = function( articleId ) {
             //console.debug("libri.bookmarklist.remove: articleId="+articleId);
            if ( articleId != null ) {
                $("#ajaxBookmarkList").load(
                        "/shop/ws/bookmarklist/remove",
                        "article="+articleId+"&forward=/action/account/bookmark/list/ajax",
                        function() {
                            //console.debug("libri.shoppingcart.remove callback");
                            $("a.addBookmark.article_"+articleId).show();
                        }
                );
            } else {
            	//console.error("libri.bookmarklist.remove: articleId is null or undefined: "+articleId);
            }
        }

        var _removeAll = function() {
            if ( confirm( 'Sind Sie sicher, dass Sie Ihren gesamten Merkzettel löschen möchten?' ) ) {
                $("#ajaxBookmarkList").load(
                        "/shop/ws/bookmarklist/removeallfrombookmarklist",
                        "forward=/action/account/bookmark/list/ajax",
                        function() {
                            //console.debug("libri.shoppingcart.removeAll callback");
                            $("a.addBookmark").show();
                        }
                );
            }
        }

        var _jumpToOffset = function( offset ) {
            //console.debug("libri.bookmarklist.jumpToOffset: "+offset);
            $("#ajaxBookmarkList").load(
                    "/shop/action/account/bookmark/list/ajax",
                    "pagerOffset="+offset
                    );
        }

        var _filter = function ( filterSelection ) {
            if ( filterSelection == null || filterSelection == "" ) {
                return;
            }
            //console.debug("libri.bookmarklist.filter: "+filterSelection);
            $("#ajaxBookmarkList").load(
                    "/shop/action/account/bookmark/list/ajax",
                    "filterSelectionId="+filterSelection
                    );
        }

        var _sort = function ( orderSelection ) {
            //console.debug("libri.bookmarklist.sort: "+orderSelection);
            $("#ajaxBookmarkList").load(
                    "/shop/action/account/bookmark/list/ajax",
                    "orderSelectionId="+orderSelection
                    );
        }
        
        var _mkurl = function(url, param) {
            var containsParam = url.indexOf( param ) >= 0;
            if ( containsParam ) {
		return url;
            }
	    var index = url.indexOf( "?" );
	    var sep = index < 0 ? "?" : "&"
	    return url+sep+param;
        }

        return {
            "show": function() {
		//console.debug("bookmarklist.show() logged in: " + libri.login.isLoggedIn());
        			if ( libri.login.isLoggedIn() ) {
        				_show();
        			} else {
        				libri.login.loggedInCall( _mkurl(window.location.href, "expandBookmarkList=true") );
        			}
        		},
            "add": function( articleId ) {
		//console.debug("bookmarklist.add() logged in: " + libri.login.isLoggedIn());
        			if ( libri.login.isLoggedIn() ) {
        				_add(articleId);
        			} else {
        				libri.login.loggedInCall( _mkurl(window.location.href, "addBookmark=" + articleId) );
        			}
        		},
            "hide": _hide,
            "remove": _remove,
            "removeAll": _removeAll,
            "jumpToOffset": _jumpToOffset,
            "filter": _filter,
            "sort": _sort
        };
    })();
}

if ( !window.libri.login ) {
    window.libri.login = (function() {
        var _loginBoxUrl;
        var _loggedIn = false;
        var _isLoggedIn = function() { return _loggedIn; };
        var _setLoggedIn = function( v ) { _loggedIn = v };

        var _rewriteUrl = function( url ) {
            if ( url.indexOf("https://") == 0 ) {
                return url;
            }
            var baseUrl = _loginBoxUrl.substring(0, _loginBoxUrl.indexOf("/shop/action") );
            return baseUrl + url.substring( url.indexOf( "/shop/action") );
        }
        
        var _submit = function( form, url ) {
            //console.log("loginSubmit(" + form + ", " + url + ")");
            try {
                //console.debug("loginSubmit: username="+form.username.value+", password="+form.password.value);
                jQuery.getJSON("/shop/ws/login/login",
                            {"username": form.username.value,
                                "password": form.password.value},
                            function( data, statusText ) {
                                 var success = data.value == "SUCCESS";
                                 //console.log("login successful: " + success);
                                 if ( success ) {
                                    _loggedIn = true;
				     if(url) {
					 window.parent.location.href = unescape(url);
				     } else {
					 window.parent.location.reload();
				     }
                                 } else {
                                	 //console.debug("XXX login: data.value="+data.value);
                                	 $("#login_box_errors ."+data.value).show();
                                 }
                            });
            } catch(err) {
		//console.log(err);
            }
            //console.log("loginSubmit() ends");
        }
        
        var _show = function( url ) {
            //console.debug("login.show: url="+url);
            var currentUrl = window.parent.location.href;
            var cancelUrl = "";
            var targetUrl = url;
            if ( !targetUrl ) {
                targetUrl = currentUrl;
            }
            if ( currentUrl.indexOf("https://") != 0 ) {
                cancelUrl = _rewriteUrl( currentUrl );
                targetUrl = _rewriteUrl( targetUrl );
            }
            fb.loadAnchor(_loginBoxUrl+"?url=" + escape(targetUrl),
                          "width: 523 height: 170 infoPos:tl shadowType:none outerBorder:0 padding:0 innerBorder:5 panelPadding:6 loadPageOnClose:`"+cancelUrl+"`",
                          "Anmelden");
        }

        var _loggedInCall = function( url ) {
            //console.debug("loggedInCall: " + url);
            if ( ! _loggedIn ) {
                _show( url );
            } else {
		if(url) {
		    window.location.href = url;
		}
            }
        }
        
        var _setLoginBoxUrl = function(url) {
            _loginBoxUrl = url;
        }

        return {
            "isLoggedIn": _isLoggedIn,
            "setLoggedIn": _setLoggedIn,
            "setLoginBoxUrl": _setLoginBoxUrl,
            "show": _show,
            "loggedInCall": _loggedInCall,
            "submit": _submit
        };
    })();
}

if ( window.libri.googlemap == null ) {
    window.libri.googlemap = (function() {
    	var map;
    	var markers = new Array();
    	var infowindows = new Array();
    	
    	var _init = function( centerLat, centerLong, mapId ) {
    		var centerlng = new google.maps.LatLng(centerLat, centerLong);
	    	var myOptions = {
			  zoom: 8,
			  center: centerlng,
			  mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			map = new google.maps.Map(document.getElementById(mapId), myOptions);
    	}
    	
    	var _addMarker = function(affiliate, image){
    		if(affiliate["latitude"] == null || affiliate["latitude"] == '' || affiliate["latitude"] == 'UNDEFINED'){
    			return;
    		}
    		if(affiliate["longitude"] == null || affiliate["longitude"] == '' || affiliate["longitude"] == 'UNDEFINED'){
    			return;
    		}
    		var latlng = new google.maps.LatLng(affiliate["latitude"], affiliate["longitude"]);
    		
    		var infowindow = new google.maps.InfoWindow({
		        content: '<div style="width:250px;"><b>'+affiliate["name"]+'</b><br><span>'+affiliate["street"]+'</span><br><span>'+affiliate["zipAndCity"]+'</span></div>',
		    	maxWidth: 400
		    });
		    infowindows[infowindows.length] = infowindow;
		
		    var marker = new google.maps.Marker({
		        position: latlng,
		        map: map,
		        icon: image,
		        title: affiliate["name"]
		    });
		    markers[markers.length] = marker;
		    
		    google.maps.event.addListener(marker, 'click', function() {
		      infowindow.open(map,marker);
		    });
    	}

    	var _setCenter = function(latitude, longitude){
    		if(latitude == null || latitude == '' || latitude == 'UNDEFINED'){
    			return;
    		}
    		if(longitude == null || longitude == '' || longitude == 'UNDEFINED'){
    			return;
    		}
    		map.setCenter(new google.maps.LatLng(latitude, longitude));
    		
		    for( i=0;i<markers.length; i++ ) {
		    	if(markers[i].position.lat().toFixed(3) == parseFloat(latitude).toFixed(3)
		    		&& markers[i].position.lng().toFixed(3) == parseFloat(longitude).toFixed(3)){
		    		infowindows[i].open(map,markers[i]);
		    	}else{
		    		infowindows[i].close();
		    	}
		    }
    	}
    	return {
            "init": _init,
            "addMarker": _addMarker,
            "setCenter": _setCenter
        };
    })();
}

