// firebugx 

if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

// end firebugX

/* typo3 compatibility */
try {
	// FF will fail if an insecure URI is called from a secure page
	if (window.location.href.indexOf('https:') < 0)
		blurLink();
	else
		blurLink = function() {};
} catch (e) {
    //blurlink is not set outside typo3
    blurLink = function() {};
}

//Check Framework Version
var netVersion = 0;
try {
	var frameworkVersions = window.navigator.userAgent.match(/\.NET CLR [\d\.]+/g);
	if (frameworkVersions && frameworkVersions.length > 0) {
		for (var i = 0; i < frameworkVersions.length; ++i) {
			var thisMatch = frameworkVersions[i].match(/\.NET CLR ([\d]+)\./g);
			var thisVersion = parseInt(RegExp.$1);
			if ((thisVersion != NaN) && (netVersion < thisVersion))
				netVersion = thisVersion;
		}
	}
} catch (e) {
	netVersion = 0;
}
		
LANG_DE = 'de';
LANG_EN = 'en';
LANG = window.location.href.match(/[&?]L=1/) ? LANG_DE : LANG_EN;

VALID_EMAIL = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;

log = function() {
    console.log(arguments);
}

$(document).ready(function() { 
    initCommands();
	$("#featuredPhotosScroller").scrollable({ size: 3, keyboard: false, clickable: false }).circular().autoscroll({interval: 6000, autopause: false});
});


initCommands = function(context) {
    context = context || $(document);
    $('.clearInput', context).titleLabeled();
    $('.jsTitleLabel', context).titleLabeled();
    $(".jsUrlDropdown", context).urlInput();
    $(".jsUrlRadio", context).urlRadio();
    $(".jsOverlay", context).overlay();
    $(".jsPagination", context).pagination();
    $(".jsCatalogFilter", context).catalogFilter();
    $(".jsToggler", context).toggler();
    $(".jsRating", context).rating();
    
    $("form.jsValidate", context).validate();
    $("form.jsAjaxPost", context).ajaxPost();
    
    $(".jsDownloadLink", context).buildDownloadLinks();
    
    $(".jsNotify", context).notifyOverlay();
    $(".jsInfobox", context).infobox();
    $(".jsAddToCart", context).cartCalculator();
    $(".jsTabbed", context).mainTabs();
    $(".jsSubTabbed", context).subTabs();
    $(".jsAutoPagination", context).autoPager();
    $(".popupClose", context).click( function(){ $(this).parent().parent().hide(); });
    $(".linkLogin", context).unbind('click').bind('click', function(){ $("#popupLogin").toggle(); });
    $(".tabInhaltElement", context).tabImageFix();
	
	if (netVersion < 2) {
		$('#textWindowsContent').hide();
		$('#textWindowsContentNet').show();
	} else {
		$('#textWindowsContentNet').hide();
		$('#textWindowsContent').show();
	}
    $('#textWindowsContent A').downloader('#downloadProcess');
    $('#textWindowsContentNet A').downloader('#downloadProcess');
    $('#networkContent A').downloader('#downloadProcess2');

    $('.tx-chnewsfeeds-pi1').fixBlogCatLinks();
    $('#list .right2 a').externalDownloadLinks();
    
    $('.c2 .featuredItem').fixRightFeaturedItems();
    
    //only available in the shop
    try {
        $(".jsLightBox", context).lightBox();
        //$(".tabbed", context).tabs();
    } catch(e) {}
}

jQuery.fn.titleLabeled = function() {
    this.each(function () {
        var node = $(this);
        if (!node.val()) node.val(node.attr('title'));
        node.focus(function() {
            var node = $(this);
            if( node.val() == node.attr('title') ) {
                node.val('');
            }
        }).blur(function() {
            var node = $(this);
            if( !node.val().length ) {
                node.val(node.attr('title'));
            }
        });
        
        //register at the form and remove label on submit
        var form = node;
        while (!form.is('form')) {
            form = form.parent();
        }
        if (!form.data('removeLabels')) {
            form.bind('submit', function() {
                $(':input', $(this)).each(function() {
                    var field = $(this);
                    if (field.hasClass('jsTitleLabel')) {
                        if (field.val() == node.attr('title')) {
                            field.val('');
                        }
                    }
                })
            });
            form.data('removeLabels', true);
        }

        return node;
    });
    return this;
};

jQuery.fn.downloader = function(target) {
    var page = $('#downloadPage');
    var target = $(target);
    this.bind('click', function(event) {
        var node = $(this);
        event.preventDefault();
        page.slideToggle("slow");
        target.slideToggle("slow");
        
        $('.downloadLink a', target).attr('href', node.attr('href'));
        setTimeout(function() {
            window.location.href=node.attr('href');
        }, 500);
    });
}

jQuery.fn.urlInput = function() {
    return this.change(function() {
        window.location.href=$(this).val();
    });
}

jQuery.fn.urlRadio = function() {
    this.bind('click', function() {
        window.location.href=$(this).val();        
    })
}

jQuery.fn.toggler = function() {
    this.each(function() {
        var node = $(this);
		var targetClass = node.attr('ajax:target');
        var target = $(targetClass);
        node.bind('click', function(event) {
			event.preventDefault();
            target.toggle('fast', function() {
				if (node.attr('id') == 'is_academic') {
					node.attr('checked', target.is(':visible'));
				} else if (node.attr('ajax:target') == '#ship_box') {
					$('#ship2diff', target).attr('checked', target.is(':visible'));
				}
            });
       });
    })
}

jQuery.fn.catalogFilter = function() {
    this.change(function() {
		var sf = $('#formSearch');
		var v = $("option:selected", this).val();
		$('#pricerange', sf).attr('value', v); 
		sf.submit();
    })
}

jQuery.fn.tabImageFix = function() {
    this.each(function() {
        var node=$(this);
        var img = $('img', node);
        if (img.length) {
            
            //check wether the image has a valid url
            if (img.attr('src').match(/\/$/)) {
                img.remove();
            }
            
            //get the h3
            var heading = $('h3', img.parent());
            if (heading.length) heading.insertBefore(img);
        }
    })
}

jQuery.fn.rating = function() {
    this.each(function() {
        var node = $(this);
        var steps = 5;
        var step = node.width() / steps;
        var target = $(node.attr('ajax:target'));
        var scls = node.attr('class');
        var curcls = scls;
        node.bind('mousemove', function(event) {
            var node = $(this);
            var left = event.clientX - node.offset().left;
            var step = node.width() / steps;
            var rating = Math.ceil(left / step);
            node.attr('class', scls);
            node.attr('ajax:rating', rating);
            node.addClass('bigRated'+rating);
        }).bind('click', function() {
             var node=$(this);
             var rating = node.attr('ajax:rating');
             curcls = node.attr('class');
             target.val(rating);
        }).bind('mouseout',function() {
             $(this).attr('class', curcls);
        }).css('cursor','pointer');
    })
}

jQuery.fn.pagination = function() {
    this.each(function() {
        var node = $(this);
        var items = $(node.attr('ajax:items'));
        var length = parseInt(node.attr('ajax:length'), 10);
        var total = parseInt(node.attr('ajax:total'), 10);
        var buttons = $('a', node);
        
        buttons.each(function(index) {
            var node=$(this);
            node.bind('click', function(event) {
                event.preventDefault();
                items.hide();
                items.slice(index*length, index*length+length).show();
                buttons.removeClass('active');
                node.addClass('active');
            });
        });
        items.slice(0, length).show();
    });
    return this;
}

jQuery.fn.overlay = function() {
    if (!$('#jsOverlay').length) {
        $('body').prepend('<div id="jsOverlay"></div>');
    };

    this.each(function(){
        var node = $(this);
		var contentClass = node.attr('ajax:content');
		
        var setOverlayEvents = function(node) {
            $('body')
                .unbind('mousedown')
                .bind('mousedown', function() {
                    node.hide();
                    $(this).unbind('mousedown');
                });
        };
        var clearOverlayEvents = function(node) {
            $('body').unbind('mousedown');
        };

        node.bind('click', function(event) {
            event.preventDefault();
            var holder = $('#jsOverlay');
            var node = $(this);
            var content = $(contentClass);
            var overlay = $('.popup', content);

            // if the overlay is not sitting in the content,
            // it is already attached
            var l = ($(window).width() - overlay.width())/2;
            var t = ($(window).height() - overlay.height())/2;
            
            overlay.css({
                left : l,
                top  : node.offset().top
            });

            if (!overlay.length) {
                holder.children().show();
                return;
            }

            overlay.show();

            //don't lose the last overlay. copy it back to the source.
            if (holder.data('prev')) {
                var source = holder.data('prev').source;
                holder.children().eq(0).appendTo(source);
            }
            holder.data('prev', {source:content});
            
            //init close buttons
            $('.jsClose', overlay).unbind("click").bind("click", function() {
                overlay.hide();
            })
            
            holder.append(overlay);
            setOverlayEvents(overlay);
            overlay.hover(function() { clearOverlayEvents($(this)); }, 
                          function() { setOverlayEvents($(this)); }
                          );
        });
		
		// remove  readme popup if empty
		if (contentClass != '.notifyPopup' && !$('.popupContent P', $(contentClass)).length  )
			node.css('visibility', 'hidden');
    });
    return this;
}

jQuery.fn.infobox = function() {
    this.each(function() {
        var node = $(this);
		var infoBoxId = node.attr('ajax:boxid');
        var infoBox = $(infoBoxId);
        node.bind('mouseover', function(event) {
			event.preventDefault();
			Tip('<div class="infobox">' + infoBox.html() + '</div>', STICKY, true);
		});
        node.bind('mouseout', function(event) {
			event.preventDefault();
            UnTip();
		});
        node.bind('click', function(event) {
			event.preventDefault();
		});
    })
}

jQuery.fn.notifyOverlay = function() {
    this.each(function() {
        var node=$(this);
        var target = $(node.attr('ajax:content'));
        var name = node.attr('ajax:name');
		var categories = node.attr('ajax:id').split(',');
        var id = 2;
		for (var i = 0; i < categories.length; i++) {
			var category = categories[i].replace(/^\s\s*/, '').replace(/\s\s*$/, '').toLowerCase();
			switch(category) {
				case 'liftlab':
					id = 6;
					break;
				case 'liftlab first':
					id = 6;
					break;
				default:
					id = 2;
			}
			if (id != 2) break;
		}
        
        node.overlay();
        node.bind('click', function() {
            $('#notification .jsName').text(name);
            $('#notification .jsId').val(id);
        })
        
    });
}

jQuery.fn.validate = function(fieldselector) {
    fieldselector = fieldselector || ':input';
    this.each(function() {
        var form = $(this);
        var append = false; //form.attr('ajax:errors') == "append";
        var fields = $(fieldselector, form);
        var validators = {
            jsEmail : function(val) {
                if (!val.toUpperCase().match(VALID_EMAIL)) {
                    return LANG == LANG_DE ? 'Keine gültige E-Mail-Adresse.' : 'No valid email address.';
                }
            },
            jsRequired : function(val) {
                if (!val) {
                    return LANG == LANG_DE ? 'Pflichtfeld.' : 'Field is required.';
                }
            },
            jsEqual : function(val, field) {
                var target = $(field.attr('ajax:target'));
                if (target.val() != val) {
                    var target = guessLabel(target);
                    var error = LANG == LANG_DE ? 'Keine Übereinstimmung mit ' : 'Does not match ';
                    return error + target;
                }
            }
        };
        
        function guessLabel(field) {
            var label = field.attr('title');
            if (!label) label = $('label[for='+field.attr('id')+']').text()
            
            return label.replace(/:?\*$/, '');
        }
        
        form.bind('submit', function() {
            var msg = [];
            fields.each(function () {
                var field = $(this);
                
                //check for titlelabeled fields
                if (field.hasClass('jsTitleLabel')) {
                    if (field.attr('title') == field.val()) {
                         field.val('');
                    }
                }
                
                for (var validator in validators) {
                    if (field.hasClass(validator) && field.is(':visible')) {
                        var valmsg = validators[validator](field.val(), field) || '';
                        if (valmsg) {
                            msg.push(guessLabel(field) + ': ' + valmsg);
                        }
                    }
                }
            });
        
            if (msg.length) {
                if (append) {
                    alert("append infos");
                } else {
                    alert(msg.join('\n'));
                }
                fields.each(function(){$(this).blur()});
                $(this).data('isValid', false);
                return false;
            } else {
                $(this).data('isValid', true);
                return true;
            }
        });
    });
    return this;
}

jQuery.fn._tabs = function(links, targets) {
    this.each(function(index) {
        targets.hide();
        links.each(function(index) {
            var node = $(this);
            node.bind('click', function(event) {
                event.preventDefault();
                var node = $(this);
                links.removeClass('activeTab');
                node.addClass('activeTab');
                targets.hide();
                targets.eq(index).show();
            });
        })
        links.eq(0).click();
    })
    return this;
}


jQuery.fn.mainTabs = function() {
    this.each(function(index) {
        var node=$(this);
        var links = $('A', node.children('UL'));
        var targets = $('DIV.tabContent', node);
        return node._tabs(links, targets);
    })
    return this;
}

jQuery.fn.subTabs = function() {
    this.each(function(index) {
        var node=$(this);
        var links = $('A', node.children('UL'));
        var targets = $('DIV.tabInhaltElement', node.next().next());
        
        return node._tabs(links, targets);
    })
    return this;
}

jQuery.fn.autoPager = function() {
    this.each(function() {
        var node = $(this);
        node.empty();
        var length = parseInt(node.attr('ajax:length'), 10);
        var total = $(node.attr('ajax:items')).length;
        node.attr('ajax:total', total);
        
        var pages = Math.ceil(total/length);
        if (pages > 1) {
            for(var i=0; i<pages;i++) {
                node.append('<a href="#">&nbsp;</a>');
            }
            node.pagination();
            $('a', node).eq(0).click();
        }
        
        
        //timebased autochanger
        var ac = node.attr('ajax:autochange')
        if (ac) {
            var cn = 0;
            var interval = parseInt(ac, 10) * 1000;
            if (node.data('toid')) clearInterval(node.data('toid'));
            var toid = setInterval(function(){
                var pages = $('a', node);
                cn++;
                if (cn >= pages.length) cn = 0;
                pages.eq(cn).click();
            }, interval);
            node.data('toid', toid);
        }
    });
}

jQuery.fn.ajaxPost = function() {
    this.each(function() {
        var node = $(this);
        node.bind("submit", function(e) {
            if (!node.data('isValid')) return; //abort if not validated
            e.preventDefault();
            data = node.serializeToObject();
            action = node.attr('action');
			var feedback;
			switch(node.attr('id'))
			{
				case 'newsletterSubscribe':
					feedback = LANG == LANG_DE ? "Vielen Dank f&uuml;r Ihre Anmeldung." : "Thank you for your subscription.";
					break;
				default:
					feedback = LANG == LANG_DE ? "Ihre Daten wurden gesendet." : "Your data was sent.";
			}
            $.post(action, data, function() {
                node.html(feedback)
                node.slideDown();
            })
            node.slideUp();
        });
    })
}

jQuery.fn.serializeToObject = function() {
    var data = {}
    $(':input', this).each(function() {
        var field = $(this);
        var name = field.attr('name');
        if (name) data[name] = field.val();
    })
    return data;
}

jQuery.fn.cartCalculator = function() {
    var node = $(this);
	var licTypeId = this.attr('ajax:licTypeId');
    var amount = $('#amount_personal, #amount_institutional');
    var licence = (licTypeId) ? $(licTypeId) : licTypeId;
    var delivery = $('#usbdelivery');
    var info = $('.thingsChosen .info');
    var totalVal = $('.total .value');
    var base = $('.base');
    var baseVal = $('.value', base);
	var save = $('.savePercentBox');
	var saveVal = $('#save_percent', save);
    var pricebase = parseFloat(this.attr('ajax:baseprice'));
    var currentprice = pricebase;
	
    function getAmountSelector() {
        return $('select[name=amount]', node);
    }
    
    function updatePrice() {
		check_options();
        var amount = getAmountSelector().val();
        
        var price = pricebase;
		var wprice = [];
		if (get_wholesale(amount, wprice))
			price = wprice['wl_price'];

        if (delivery && delivery.length) {
            var modifier = $(':selected', delivery).attr('ajax:modifier');
            price += parseFloat(modifier);
        }
        if (licence && licence.length) {
            var modifier = $(':selected', licence).attr('ajax:modifier');
            price += parseFloat(modifier);
        }
        
        currentprice = price * parseInt(amount, 10);
		var listPriceSum = list_price * parseInt(amount, 10);
		var savedPercent = 100 - (100 * currentprice / listPriceSum);
		//alert(currentprice + "-" + listPriceSum + "-" + savedPercent);
        totalVal.text(currentprice.toFixed(2));
        baseVal.text(listPriceSum.toFixed(2));
        saveVal.text(savedPercent.toFixed(0));
		if (currentprice != listPriceSum) {
			base.show();
			save.show();
		} else {
			base.hide();
			save.hide();
		}
    }
    
    function setLicenseType(type) {
        var active = $('#amount_'+type);
        var inactive = type == 'personal' ? $('#amount_institutional') : $('#amount_personal');
        var deliveryCtrl = $('#deliveryCtrl');
		var usbdelivery = document.getElementById("usbdelivery");

        //display the right amount selector
        inactive.hide();
        inactive.attr('name', 'amount_inactive');
        active.show();
        active.attr('name', 'amount');
	
		//(de)activate delivery
		if (type == 'personal') {
			deliveryCtrl.show();
		} else if (type == 'institutional') {
			usbdelivery.selectedIndex = 0;
			deliveryCtrl.hide();
		}
        
        //activate the right option
		var cartBox = $('#boxAddToCart');
        var lsel = $('#' + cartBox.attr('ajax:licTypeId'), cartBox);
        var alic;
        $('option', lsel).each(function() {
            if ($(this).text().toLowerCase() == type.toLowerCase()) alic = $(this).attr('value');
        })
        lsel.val(alic);
        
        updatePrice();
        updateInfo();
    }
    
    function updateInfo() {
        var text = [$(':selected', getAmountSelector()).text()];
        if (delivery.val() == 4188 && currentprice > pricebase) {
            text = text.concat([
                '+',
                'USB Delivery'
            ])
        }
        info.text(text.join(" "));
    }

    //check the tabs
    var tabs = $('ul li', node);
    var tabLinks = $('ul a', node);
    if (tabs.length > 1) {
        tabLinks.bind('click', function(event) {
            var node = $(this);
            tabs.removeClass('ui-state-active');
            node.parent().addClass('ui-state-active');
            setLicenseType(node.attr('ajax:licence'));
			updatePrice();
        })
    }
    
    amount.bind("change", function() {
        updatePrice();
        updateInfo();
    });
    
    if (delivery.length) {
        delivery.bind("change", function() {
            updatePrice();
            updateInfo();
        })
    }
    
    return this;
}

jQuery.fn.fixBlogCatLinks = function() {
    this.each(function() {
        var node = $(this);
        if ($(node).data('isInit')) return;
        $('a', node).each(function() {
            var link = $(this);
            var url = link.attr('href');
            //create rss link
            link.parent().css('position', 'relative');
            link.after('<span class="rss"></span>')
            var rsslink = $('span', link.parent());
            rsslink.css({
                'display' : 'block',
                'position' : 'absolute',
                'right' : '0px',
                'top' : '0px',
                'width' : '16px',
                'height' : '16px',
                'cursor' : 'pointer'
            })
            .bind('click', function() {
                window.location.href = $(this).attr('ajax:href');
            })

            //modify url
            link.attr('href', url.replace(/\/newsletter-archive\/[^\/]+/, '').replace(/\/rss\.xml/, '.html'));
        });
        $(node).data('isInit', true);
    })
}

jQuery.fn.externalDownloadLinks = function() {
    this.each(function() {
        var node = $(this);
        if (node.attr('href').match(/\.link$/)) {
            node.bind('click', function(event) {
                event.preventDefault();
                var url = $(this).attr('href');
                $.get(url, function(response) {
                    window.location.href = response;
                })
            })
        }
    })
}

jQuery.fn.fixRightFeaturedItems = function() {
    this.each(function() {
        var node = $(this);
        var img = $('img', node);
        if (img.length > 1) {
            img.css({
                'backgroundImage' : node.css('backgroundImage'),
                'border' : 'none',
                'padding' : '0 5px 5px 5px'
            });
            node.css({
                'background' : 'none',
                'margin-bottom' : '30px'
            })
        }
    });
}

jQuery.fn.buildDownloadLinks = function() {
    this.each(function() {
        var node = $(this);
        var versionNode = $('div.version', this);
		versionNode.empty();
		var dLink = node.attr('ajax:d-link');
		var qLink = node.attr('ajax:q-link');
		var defVersion = node.attr('ajax:def-version');
		if (dLink != '') {
			node.prepend(dLink);
			versionNode.html(defVersion);
		} else {
			node.prepend(qLink);
			var anchor = $('a', node);
			var dataUri = anchor.attr('href');
			// FF will fail if an insecure URI is called from a secure page
			if (window.location.href.indexOf('https:') == 0) {
				dataUri = dataUri.replace(/^http:/, 'https:');
			}
			var href = dataUri.replace(/[^\/]+\.application$/, '');
			anchor.attr('href', href);
			$.get(dataUri, function(manifest) {
				var versions = manifest.match(/assemblyIdentity .* version="([\d\.]+)"/);
				if (versions)
					versionNode.html('V ' + RegExp.$1);
				else
					versionNode.html(defVersion);
			}, "text");
		}
    });
}

