
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(
            'http://images.libri.de/shop/logos/mozsearch/' + urlNr + '.src',
            'http://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 winOpenKalender() {
    window.open("http://www.adventskalender.mediastyle.de/user2007/books-ch/advent/adventskalender.asp","","width=700,height=600,top=20,left=20,menubar=no,scrollbars=no,resizable=no,directories=no,location=no,status=no,toolbar=no");
}

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 _loggedIn = false;
        var _isLoggedIn = function() { return _loggedIn; };
        var _setLoggedIn = function( v ) { _loggedIn = v };

        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);
            fb.loadAnchor("/shop/action/account/loginbox?url=" + escape(url),
                          "width: 523 height: 170 infoPos:tl shadowType:none outerBorder:0 padding:0 innerBorder:5 panelPadding:6",
                          "Anmelden");
        }

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

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